In this article, we will be seeing differences between toBe() and toEqual() in jasmine.
In Jasmine, toBe() and toEqual() are two different methods used to make test assertions.
- toBe() is a matcher used to test for strict equality between two values.
- It checks if the value returned by the code is the same object as the expected value.
- This means that the values must have the same type and value.
expect(5).toBe(5); // passes
expect('hello').toBe('hello'); // passes
expect(5).toBe('5'); // fails
- In the third example, the test fails because the values are not strictly equal since they have different types (a number and a string).
- toEqual() is a matcher used to test for deep equality between two values.
- It checks if the value returned by the code equals the expected value by recursively comparing objects' properties and arrays' values.
expect(5).toEqual(5); // passes
expect('hello').toEqual('hello'); // passes
expect(5).toEqual('5'); // fails
expect([1,2,3]).toEqual([1,2,3]); // passes
expect({a: 1, b: 2}).toEqual({b: 2, a: 1}); // passes
- In the third example, the test fails because the values are not profoundly equal since they have different types.
- In the last example, the test passes even though the order of properties is different in the actual and expected objects because the comparison is made recursively.
Equality:
- toBe() tests for strict equality.
- toEqual() tests for deep equality.
Value:
- toBe() checks if the value returned by the code is the same object as the expected value.
- toEqual() compares the properties of the object and values of an array.
Check:
- toBe() checks the same type and value.
- toEqual() checks for the same value.
Testing:
- toBe() is used to test primitive values like strings and numbers.
- toEqual() is used to test objects and arrays.
Speed:
- toBe() is faster than toEqual() since it performs simple equality checks.
- toEqual() performs the recursive comparison.
- Log in to post comments