Checking for Equality
Explore how to effectively test object equality in Jest using various matchers. Understand the differences between toBe, toStrictEqual, toEqual, and toMatchObject and learn when to use each for comprehensive and resilient React app testing.
We'll cover the following...
A failing equality test
The project for this lesson will be a little familiar from the last lesson. The difference from the last lesson is that we are checking the returned objects using the toBe matcher:
expect(person).toBe({
id: 1,
firstName: "Bill",
lastName: "Peters",
});
A copy of the starter project is in the code widget below:
import { getCompany } from "./data";
test("Should return correct company object when found", async () => {
const company = await getCompany(1);
expect(company).toBe({
id: 1,
name: "Dibbert Group",
});
});
Run the tests in the terminal by running the following command:
npm test
Press the “Run” button to open the terminal when using the code widget above. Both the tests fail.
Jest gives us a clue for how to resolve this with its message:
If it should pass with deep equality, replace “toBe” with “toStrictEqual”.
The problem is ...