1
votes

I expected the following sample test to fail if I use toEqual(), but it passes:

it('sample test to check toEqual and toBe', () => {
   const expectedAction = {test: '123', value: undefined};
   const actualAction = {test: '123'};
   expect(expectedAction).toEqual(actualAction);
}) 

The same test fails if I use .toBe(). However, if I fix the test case like this:

it('sample test to check toEqual and toBe', () => {
   const expectedAction = {test: '123', value: '123'};
   const actualAction = {test: '123', '123'};
   expect(expectedAction).toBe(actualAction);
});

it again fails saying that "Compared values have no visual difference".

Is the behaviour correct? How to modify my test case so that it fails correctly.

2

2 Answers

2
votes

If you really need it to be considered as different, one option would be to use Jest snapshot test, like:

expect(expectedAction).toMatchSnapshot();

The first time, it will create a snapshot file and print the javascript object to it, when you run the test again, it will compare it to the snapshot. Most of the times, the snapshots are used to compare the component rendered tree, but you can use it for any javascript object.

1
votes

The first one passes cause toEqual compares every element of your objects with each other, so in your case

expectedAction.test === actualAction.test

as both are '123'

but the same is true for

expectedAction.value === actualAction.value

as both are undefined

The second test fails cause toBe uses === to compare the two objects which will of cause fail as they are not the same instances. The only way that an object will passes toBe would be to use itself for comparison:

expect(expectedAction).toBe(expectedAction)