Assertions
Every expect() matcher in @axiljs/testing: equality, objects, arrays, numbers, errors, promises with resolves and rejects, and mock call matchers, by example.
On this page10
expect(value) from @axiljs/testing returns a set of chainable matchers in the Jest style. A matcher that fails throws an AssertionError with a message that shows the actual and expected values; the test runner catches it and reports the test as failed. There are no dependencies.
1import { describe, it, expect } from '@axiljs/testing'
2
3describe('cart', () => {
4 it('totals line items', () => {
5 const cart = { items: [{ sku: 'A1', qty: 2 }], total: 4200 }
6
7 expect(cart.total).toBe(4200)
8 expect(cart.items).toHaveLength(1)
9 expect(cart).toMatchObject({ items: [{ sku: 'A1' }] })
10 expect(cart).not.toHaveProperty('discount')
11 })
12})Modifiers
| Modifier | Effect |
|---|---|
.not | Inverts the next matcher: expect(x).not.toBe(0) |
.resolves | Awaits a promise and runs the matcher on the resolved value. Returns a Promise; await it |
.rejects | Expects the promise to reject and runs the matcher on the rejection reason. Returns a Promise; await it |
.resolves and .rejects accept a promise or a function that returns one. Both expect(p).not.resolves.toBe(1) and expect(p).resolves.not.toBe(1) work.
Equality
| Matcher | Passes when |
|---|---|
toBe(expected) | actual === expected |
toEqual(expected) | Values are deeply equal (see below) |
toMatchObject(subset) | actual contains every property in subset, recursively |
expect(1 + 1).toBe(2)
expect({ id: 1, tags: ['a'] }).toEqual({ id: 1, tags: ['a'] })
expect({ id: 1, name: 'Ada', role: 'admin' }).toMatchObject({ role: 'admin' })How toEqual compares:
- Arrays: same length, and each item deeply equal.
- Objects: the same number of own enumerable keys, and each value deeply equal. Prototypes are ignored, so a class instance equals a plain object with the same fields.
Dateby time,RegExpby source and flags,MapandSetby contents.NaNequalsNaN.- A key set to
undefinedstill counts.{ a: 1, b: undefined }does not equal{ a: 1 }, which is stricter than Jest.
How toMatchObject compares: extra properties on the actual object are allowed at every level, but arrays must have the same length, with each item matched as a subset. Date, RegExp, Map and Set values in the subset are compared with toEqual rules.
Truthiness and types
| Matcher | Passes when |
|---|---|
toBeTruthy() | !!actual is true |
toBeFalsy() | !actual is true |
toBeNull() | actual === null |
toBeUndefined() | actual === undefined |
toBeDefined() | actual !== undefined |
toBeNaN() | Number.isNaN(actual) |
toBeInstanceOf(Class) | actual instanceof Class |
1import { NotFoundError } from '@axiljs/core'
2
3expect(err).toBeInstanceOf(NotFoundError)
4expect(user.deletedAt).toBeNull()Numbers
| Matcher | Passes when |
|---|---|
toBeGreaterThan(n) | actual > n |
toBeGreaterThanOrEqual(n) | actual >= n |
toBeLessThan(n) | actual < n |
toBeLessThanOrEqual(n) | actual <= n |
toBeCloseTo(expected, numDigits = 2) | The absolute difference is below 10^-numDigits / 2 (both Infinity or both -Infinity also pass) |
The comparison matchers accept number or bigint. Use toBeCloseTo for floating point:
expect(0.1 + 0.2).toBeCloseTo(0.3) // passes; toBe(0.3) would fail
expect(Math.PI).toBeCloseTo(3.1416, 4)Strings, arrays and objects
| Matcher | Passes when |
|---|---|
toHaveLength(n) | actual.length === n (arrays, strings, anything with length) |
toContain(item) | A string contains the substring, or an array or other iterable contains the item (===) |
toContainEqual(item) | An array or iterable contains an item deeply equal to item |
toMatch(pattern) | actual is a string that contains pattern (a string) or matches it (a RegExp) |
toHaveProperty(path, value?) | The property exists; with value, it is also deeply equal |
1expect('hello world').toContain('world')
2expect(new Set(['a', 'b'])).toContain('a')
3expect([{ id: 1 }, { id: 2 }]).toContainEqual({ id: 2 })
4expect(res.body.message).toMatch(/created/i)toHaveProperty takes a path string with dots and indexes, or an array of keys. Inherited properties count.
1const body = { data: { users: [{ name: 'Ada' }] } }
2
3expect(body).toHaveProperty('data.users[0].name', 'Ada')
4expect(body).toHaveProperty(['data', 'users', 0, 'name'])Errors
toThrow(expected?) calls the function you pass and checks that it throws. Wrap the call in an arrow function; passing a value that is not a function is itself an error.
expected | Passes when the thrown error |
|---|---|
| omitted | is anything |
string | has a message that contains the string |
RegExp | has a message matching the pattern |
| an error class | is an instance of the class |
an Error instance | has exactly the same message |
1expect(() => parseAmount('abc')).toThrow()
2expect(() => parseAmount('abc')).toThrow('Invalid amount')
3expect(() => parseAmount('abc')).toThrow(/amount/)
4expect(() => parseAmount('abc')).toThrow(RangeError)
5expect(() => parseAmount('1')).not.toThrow()Promises
1await expect(repo.findById(1)).resolves.toEqual({ id: 1, name: 'Ada' })
2await expect(repo.findById(999)).rejects.toThrow('not found')
3await expect(repo.findById(999)).rejects.toBeInstanceOf(NotFoundError)
4
5// a function returning a promise also works
6await expect(() => repo.findById(1)).resolves.toHaveProperty('id', 1)rejects.toThrow() checks the rejection reason directly with the same rules as toThrow(). Any other matcher after .rejects runs against the reason, so rejects.toMatchObject({ code: 'NOT_FOUND' }) checks the error's fields.
If the promise settles the other way (rejects under .resolves, or resolves under .rejects), the assertion fails with a message saying so.
Note
Always await (or return) an assertion that uses .resolves or .rejects. Without it the test finishes before the promise settles, and a failure is never reported.
Mock functions
These matchers work on mocks created with fn() or spyOn(), described in Mock functions. On a plain function they throw an AssertionError.
| Matcher | Passes when |
|---|---|
toHaveBeenCalled() | The mock was called at least once |
toHaveBeenCalledTimes(n) | It was called exactly n times |
toHaveBeenCalledWith(...args) | At least one call had arguments deeply equal to args |
toHaveBeenLastCalledWith(...args) | The most recent call had arguments deeply equal to args |
1import { fn, expect } from '@axiljs/testing'
2
3const send = fn()
4await notifyUser(send, { id: 1, email: 'ada@example.com' })
5
6expect(send).toHaveBeenCalledTimes(1)
7expect(send).toHaveBeenCalledWith('ada@example.com', 'Welcome!')AssertionError
Every failed matcher throws AssertionError (exported from @axiljs/testing), with name set to 'AssertionError'. You can throw it yourself from a custom check, and the runner reports it the same way:
1import { AssertionError } from '@axiljs/testing'
2
3function expectSorted(list: number[]) {
4 for (let i = 1; i < list.length; i++) {
5 if (list[i] < list[i - 1]) throw new AssertionError(`Not sorted at index ${i}`)
6 }
7}Related
- Test runner
- Mock functions
- HTTP test client
- Request context: testing code that calls
getContext()
Was this page helpful?