Your test fails (it shows red), and the message says expected { name: 'Budi', age: 25 } to be { name: 'Budi', age: 25 }. Left and right look exactly the same. Your code is right. What went wrong is how they were compared.
How they are compared is set by the matcher: the method you chain onto expect(...), such as toBe, toEqual and toContain. One line of expect(...).matcher(...) is called an assertion: a statement that must be true for the test to pass. Picture checking a parcel in two ways. The first way: is this the box that was sent, with the same tracking number? The second way: does it hold the same items as the order list? Two different boxes can hold exactly the same items. In code, the box is an object, and what is in the box is its properties and their values. toBe checks in the first way, toEqual in the second.
toBe vs toEqual
In the code below, user is an object with two properties, and three assertions check it:
const user = { name: "Budi", age: 25 };
expect(user.age).toBe(25); // passes
expect(user).toEqual({ name: "Budi", age: 25 }); // passes
expect(user).toBe({ name: "Budi", age: 25 }); // fails
toBechecks whether two values are identical, like===(precisely,Object.is). For numbers, strings and booleans, the same value means identical, sotoBe(25)passes.- For objects and arrays, the rule is different. The
{ name: "Budi", age: 25 }written insidetoBe(...)is a new object: another box, even with the same contents. SotoBefails. toEqualcompares the contents deeply (deep equality): every property, and everything inside that property. The order of the properties doesn't matter.
For the third assertion, the one that fails, Vitest reports:
× matchers.test.js > user 1ms
→ expected { name: 'Budi', age: 25 } to be { name: 'Budi', age: 25 } // Object.is equality
If it should pass with deep equality, replace "toBe" with "toStrictEqual"
Expected: { name: 'Budi', age: 25 }
Received: serializes to the same string
serializes to the same string means that both objects turn into exactly the same text. The contents are the same, but the objects are different, which is why toBe fails. Vitest suggests toStrictEqual, a stricter toEqual: toStrictEqual also checks properties set to undefined and the class that made the object. The guideline: toBe for numbers, strings and booleans, toEqual for objects and arrays.
What arrays, objects and text hold
The matchers below check contents. fruits is an array of three fruits, and user is the object from the example before:
const fruits = ["apple", "orange", "mango"];
expect(fruits).toContain("apple"); // "apple" is in it
expect(fruits).toHaveLength(3); // its length is 3
expect(user).toMatchObject({ name: "Budi" }); // some of its properties match
expect(user).toHaveProperty("age", 25); // has an age property set to 25
expect("Hello World").toContain("World"); // a piece of text
expect("Hello World").toMatch(/^Hello/); // matches a regex
/^Hello/ is a regex (a text pattern), and it means "starts with Hello". When an assertion on an array fails, the message names what the array holds. For example, toContain("durian") fails with expected [ 'apple', 'orange', 'mango' ] to include 'durian', and toHaveLength(4) fails with expected [ 'apple', 'orange', 'mango' ] to have a length of 4 but got 3.
True or false, null, and numbers
The matchers below check the kind of value, and numbers. result is any value you want to check:
expect(result).toBeTruthy(); // JavaScript treats it as true
expect(result).toBeFalsy(); // false, 0, "", null, undefined or NaN
expect(result).toBeNull(); // exactly null
expect(result).toBeUndefined(); // exactly undefined
expect(result).toBeDefined(); // anything but undefined
expect(10).toBeGreaterThan(5);
expect(3).toBeLessThanOrEqual(3);
expect(0.1 + 0.2).toBeCloseTo(0.3); // passes
expect(0.1 + 0.2).toBe(0.3); // fails: the result is 0.30000000000000004
Truthy means JavaScript treats the value as true: every value that is not falsy (treated as false). There are six common falsy values: false, 0, "", null, undefined and NaN. toBeGreaterThan(5) means greater than 5, and toBeLessThanOrEqual(3) means less than or equal to 3. Computers store decimals in binary, so 0.1 + 0.2 misses 0.3 by a tiny bit. toBeCloseTo treats two numbers as equal as long as the difference is small. By default, a difference of less than 0.005 counts as equal.
toThrow: wrap the function
divide below throws an error when the number you divide by is 0. There are three ways to check it, and only two are right:
function divide(a, b) {
if (b === 0) throw new Error("Cannot divide by zero");
return a / b;
}
expect(() => divide(10, 0)).toThrow(); // passes
expect(() => divide(10, 0)).toThrow("Cannot divide by zero"); // passes, the message matches
expect(divide(10, 0)).toThrow(); // the test blows up first
() => divide(10, 0)is a function that hasn't run yet.expect(...).toThrow()calls it, catches its error, then checks it.- Without the wrapper,
divide(10, 0)runs first. Its error is thrown beforeexpectcan catch it, so the test fails with the messageCannot divide by zero. - The text in
toThrow("...")is matched as a piece of the error message: the message only has to contain that text. A regex works too:toThrow(/zero/).
.not flips a matcher
.not before a matcher flips its result: the assertion passes when the matcher does not match.
expect(5).not.toBe(3);
expect(fruits).not.toContain("durian");
expect(result).not.toBeNull();
Behind the scenes: a matcher is just a function
To see how matchers work, you can build a mini expect of your own. In this version, each matcher only returns true or false:
function expect(value) {
return {
toBe(expected) {
return value === expected;
},
toEqual(expected) {
return JSON.stringify(value) === JSON.stringify(expected);
},
not: {
toBe(expected) {
return value !== expected;
},
},
};
}
console.log(expect(5).not.toBe(3)); // true
console.log(expect({ a: 1 }).toEqual({ a: 2 })); // false
expect(value)returns an object full of matchers. Each matcher can still readvalue, even afterexpecthas finished running.JSON.stringifyturns both sides into text, so their contents can be compared with===.notholds versions whose result is flipped, including when the original result isfalse.
Real Vitest works a little differently. A matcher that fails throws an error, and that error is what makes the test fail (red). Real toEqual doesn't use JSON.stringify either, because { a: 1, b: 2 } and { b: 2, a: 1 } turn into different text even though their contents are the same.
⚠️ Picking the wrong matcher
toBefor an object or array. It always fails when the objects are made separately. UsetoEqual.- Calling the function directly in
toThrow.expect(divide(10, 0))throws the error before anything is checked. Wrap it in a function:expect(() => divide(10, 0)). toBefor decimals.0.1 + 0.2is not exactly0.3. UsetoBeCloseTo.- A matcher that is too loose.
toBeTruthy()also passes for"error". Pick the most specific one:toBeNull(),toBe(25),toHaveLength(3).
TL;DR: A matcher is a method you chain onto expect(...), and it decides how the values are compared. toBe checks for identical values (like ===) for numbers, strings and booleans. expect({ a: 1 }).toBe({ a: 1 }) fails: they are two separate objects, even with the same contents. toEqual compares the contents of objects and arrays deeply. toContain checks what an array or text holds, toHaveLength its length, toBeTruthy, toBeNull and toBeUndefined the kind of value, toBeGreaterThan and toBeCloseTo numbers. toThrow checks for an error, and the function you test must be wrapped in () =>. .not flips any matcher.
⚡ toBe or toEqual
Write:
const user = { name: "Budi", age: 25 };
expect(user.age).toBe(25); // passes
expect(user).toEqual({ name: "Budi", age: 25 }); // passes
expect(user).toBe({ name: "Budi", age: 25 }); // fails
Guess first: the contents are exactly the same, so why does the third line fail?
The object written inside toBe(...) is a new object, separate from user, even with the same contents. toBe checks whether the two are the same object, like ===.
Meaning: expect(...) keeps the value to check, and a matcher such as toBe or toEqual decides how to compare it. toBe is for numbers, strings and booleans. toEqual compares the contents of objects and arrays deeply.
⚡ What arrays and text hold
Write:
expect(fruits).toContain("apple");
expect(fruits).toHaveLength(3);
Meaning: fruits is the array ["apple", "orange", "mango"]. toContain checks whether one item is in an array or a piece of text, and toHaveLength checks its length.
⚡ toThrow: wrap the function
Write:
expect(() => divide(10, 0)).toThrow("Cannot divide by zero");
Guess first: divide(10, 0) throws an error. If you write expect(divide(10, 0)).toThrow(), with no () =>, what happens?
The test fails because of that error. divide(10, 0) runs first, so its error is thrown before expect gets the chance to catch it.
Meaning: () => divide(10, 0) is a function that hasn't run yet. expect(...).toThrow() calls it, catches its error, then checks it. The error message must contain the text in toThrow(...).