Expect and Matchers
So you have your test() function set up. Now you need to actually check if something is right. That is where expect() and matchers come in. Think of expect() as you making a claim, and matchers as the proof.
Let me give you the most common matchers you will use every day. Once you memorize these, writing tests becomes second nature.
toBe - Strict Equality
toBe checks if two values are exactly the same. It uses something called Object.is under the hood, which is like strict equality (===) but handles a few edge cases better.
test('toBe checks strict equality', () => {
expect(2 + 2).toBe(4);
expect('hello').toBe('hello');
expect(true).toBe(true);
expect(null).toBe(null);
});
toEqual - Deep Comparison
toEqual checks if two objects or arrays have the same content. It does a deep comparison instead of checking if they are the exact same reference.
test('toEqual compares object contents', () => {
expect({ name: 'Alice', age: 25 }).toEqual({ name: 'Alice', age: 25 });
expect([1, 2, 3]).toEqual([1, 2, 3]);
});
Truthiness Matchers
These check if values are truthy, falsy, or undefined. Super useful for checking defaults and optional values.
test('truthiness matchers', () => {
expect('not empty').toBeTruthy();
expect('').toBeFalsy();
expect(undefined).toBeUndefined();
expect(null).toBeNull();
expect(42).toBeDefined();
});
Numeric Comparisons
When you work with numbers that are not exact, these matchers save the day.
test('numeric matchers', () => {
expect(10).toBeGreaterThan(5);
expect(3).toBeLessThan(10);
expect(0.1 + 0.2).toBeCloseTo(0.3);
});
That toBeCloseTo one is important. Floating point math is weird in JavaScript, so 0.1 + 0.2 does not exactly equal 0.3. toBeCloseTo handles that for you.
Try it Yourself →Key Takeaways
- expect() is how you make a claim about your code
- toBe checks strict equality, use it for primitives
- toEqual does deep comparison, use it for objects and arrays
- Truthy/falsy matchers check boolean-like values
- Use toBeCloseTo for floating point comparisons