Leena
Leena

Reputation: 11

How to write jasmine test

I am writing a unit test for Angular2 in Jasmine.

Here is my code snippet:

component.ts

toggleSelect() {
    this.checked = event.target.checked
    this.tree.forEach(t => {
     t.checked = this.checked
    })
  }

Upvotes: 0

Views: 73

Answers (1)

JeanPaul A.
JeanPaul A.

Reputation: 3724

The error message "Expected true to be false." means that jasmine is expecting the value of a variable to be false, but the actual value is true.

From the code snippet above, this error is only possible when doing assertion in the following code block

component.tree.forEach(t => {
   expect(t.checked).toBe(false);
});

where the checked flag is expected to be false, but it is actually true.

From the code provided, I think this is a result of the following line of code (in the test).

component.toggleSelect(event);

The event that is passed has a checked value of true. When toggleSelect is called with the event object, the checked value of each entry in the tree array is set to true. As a result of this, the first assertion represented by the code block

component.tree.forEach(t => {
   expect(t.checked).toBe(true);
});

is successful.

However following that assertion, you are not calling

component.toggleSelect(event);

with an event object whose checked value is false.

This would result in the previous state of the tree being preserved.

To fix your test, all you need to do is call the following piece of code before the assertion that is failing

event.target.checked = false; // Set the checked value to false
component.toggleSelect(event); // Call toggle select with the updated event

Upvotes: 3

Related Questions