Let's start with basic equality tests.
For exact matches (same as 1 === 1
in regular JavaScript code), you can use .toBe(expectedValue)
.
test('basic equality', () => {
const result = 2 + 2;
expect(result).toBe(4);
expect(0).toBe(0);
});
Another common thing to do when checking numbers is to do less than (1 < 2
) or greater than (2 > 1
).
You can do this with these functions in Jest and Vitest:
toBeGreaterThan(x)
toBeGreaterThanOrEqual(x)
toBeLessThan(x)
toBeLessThanOrEqual(x)
test('comparison matchers', () => {
const score = 85;
expect(score).toBeGreaterThan(80);
expect(score).toBeGreaterThanOrEqual(
85
);
expect(score).toBeLessThan(100);
expect(score).toBeLessThanOrEqual(85);
expect(score > 80).toBe(true);
});
Numbers are not always precise in JavaScript. The famous example is 0.1 + 0.1 + 0.1
in Javascript is a little bit bigger than 0.3!
This test will fail:
expect(0.1 + 0.1 + 0.1).toBe(0.3);
For those numbers, you can use .toBeCloseTo(0.3)
It also takes a 2nd argument so you can define how many decimals to compare to. The default is 2 btw
test('showing toBeCloseTo precision argument', () => {
const result = 1 / 3;
expect(result).toBeCloseTo(0.33, 2);
expect(result).toBeCloseTo(0.333, 3);
expect(result).toBeCloseTo(0.3333, 4);
});
Why does this happen? You might expect 0.1 + 0.1 + 0.1 === 0.3.
But internally, JavaScript uses IEEE-754 double-precision floating-point numbers, which means that some decimal numbers (like 0.3333333...) can't be represented exactly, which leads to issues like this.
The other special number matcher to be aware of is the .toBeNaN()
function
test('special number values', () => {
expect(NaN).toBeNaN();
});
You might also need to compare positive and negative infinity. This can be done with the .toBe()
function
test('infinity checks', () => {
expect(Infinity).toBe(Infinity);
expect(-Infinity).toBe(-Infinity);
});
Lesson Task
Complete the three incomplete tests.
Use a mix of .toBeGreaterThan(...)
, .toBeCloseTo(...)
, and .toBeNaN()
.