You can think of the toBe
matcher as ===
.
The toBe()
matcher is used to test for strict equality between two values.
It checks if the expected value and the actual value are the same using the strict equality operator (===
). This matcher is particularly useful when working with primitive data types like numbers, strings, and booleans.
test('adds 1 + 2 to equal 3', () => {
expect(1 + 2).toBe(3);
});
test('numbers', () => {
expect(42).toBe(42);
expect(-5).toBe(-5);
});
test('true is ... true!', () => {
expect(true).toBe(true);
expect(!false).toBe(true);
expect([].length === 0).toBe(true);
expect([].length === 999).toBe(false);
});
test('strings', () => {
expect('a').toBe('a');
expect('hello world').toBe(
'hello world'
);
});
test('null and undefined', () => {
expect(null).toBe(null);
expect(undefined).toBe(undefined);
});
test('objects', () => {
const object = { hi: 'hi' };
const sameReference = object;
expect(object).toBe(object);
expect(object).toBe(sameReference);
});
Use toEqual()
to check that arrays or objects are equal in their values.
(Note: there will be more in-depth lessons on this when testing arrays and objects*)
test('object assignment', () => {
const data = { one: 1 };
data['two'] = 2;
expect(data).toEqual({
one: 1,
two: 2,
});
});
The toBeTruthy()
and toBeFalsy()
matchers are used to test whether a value is considered truthy or falsy.
test('falsy values', () => {
expect(null).toBeFalsy();
expect(0).toBeFalsy();
expect('').toBeFalsy();
});
test('truthy values', () => {
expect('some string').toBeTruthy();
expect([]).toBeTruthy();
expect({}).toBeTruthy();
});
test('can also test true/false', () => {
expect(true).toBeTruthy();
const isLessThan2 = 1 < 2;
expect(isLessThan2).toBeTruthy();
expect(false).toBeFalsy();
});
Personally I don't use this often, as I'll try to just use expect(something).toBe(true)
, or expect(something).toBe(0)
.
But it is useful when you care about something like ''
, 0
, null
etc being falsy.
The toBeNull()
matcher is used to test whether a value is null
.
test('null value', () => {
expect(null).toBeNull();
});
This works in a very similar way to toBeNull()
. It will check that the value is === undefined
test('undefined value', () => {
expect(undefined).toBeUndefined();
const returnNothing = () => undefined;
expect(
returnNothing()
).toBeUndefined();
});
This is like the opposite of toBeUndefined()
. It basically checks if your value !== undefined
.
test('defined value', () => {
expect('test').toBeDefined();
expect([]).toBeDefined();
expect(null).toBeDefined();
});
A note on null with toBeDefined(): Since toBeDefined()
checks if a value is not undefined
, it's important to understand that null
is considered a defined value when it comes to toBeDefined()
.
Lesson Task
In the test runner (use the tabs aboveon the right) there are a bunch of half written assertions.
Fill each one out, with the suggested matcher.