JEST expect function
Basic Usage
In the Jest framework,expectis a function used to create assertions in tests. Assertions are statements that evaluate whether a given condition is true. If the condition is false, the test fails.
Theexpectfunction is central to writing tests in Jest, providing a wide array of matchers to perform assertions on various data types and structures.
Here's a breakdown of howexpectworks and its common usage,expect(value)Common Matchers
i) toBe(value): Checks for strict equality usingObject.is.expect(2 + 2).toBe(4);ii) toEqual(value): Checks for deep equality. Useful for comparing objects and arrays.
const obj = { a: 1, b: 2 }; expect(obj).toEqual({ a: 1, b: 2 });iii) toBeNull(): Checks if the value is
null.expect(null).toBeNull();iv) toBeUndefined(): Checks if the value is
undefined.expect(undefined).toBeUndefined();v) toBeDefined(): Checks if the value is defined.
expect(definedValue).toBeDefined();vi) toBeTruthy(): Checks if the value is truthy.
expect(true).toBeTruthy();vii) toBeFalsy(): Checks if the value is falsy.
expect(false).toBeFalsy();viii) toContain(item): Checks if an array or iterable contains the specified item.
expect([1, 2, 3]).toContain(2);ix) toHaveLength(number): Checks the length of an array or string.
expect('hello').toHaveLength(5);x) toMatch(regexpOrString): Checks if a string matches a regular expression or string.
expect('hello world').toMatch(/world/);Asynchronous Code
i) Async/Awaittest('fetches data', async () => { const data = await fetchData(); expect(data).toBeDefined(); });ii) .resolves / .rejects
test('fetches data resolves', () => { return expect(fetchData()).resolves.toBe('data'); }); test('fetches data rejects', () => { return expect(fetchData()).rejects.toMatch('error'); });Custom Matchers
You can also define custom matchers to extend Jest's functionality
expect.extend({ toBeWithinRange(received, floor, ceiling) { const pass = received >= floor && received <= ceiling; if (pass) { return { message: () => `expected ${received} not to be within range ${floor} - ${ceiling}`, pass: true, }; } else { return { message: () => `expected ${received} to be within range ${floor} - ${ceiling}`, pass: false, }; } }, }); test('numeric ranges', () => { expect(100).toBeWithinRange(90, 110); });