Testing

Assertions

Every expect() matcher in @axiljs/testing: equality, objects, arrays, numbers, errors, promises with resolves and rejects, and mock call matchers, by example.

6 min readUpdated DocumentationEdit this page
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.

TypeScript
TS
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

ModifierEffect
.notInverts the next matcher: expect(x).not.toBe(0)
.resolvesAwaits a promise and runs the matcher on the resolved value. Returns a Promise; await it
.rejectsExpects 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

MatcherPasses when
toBe(expected)actual === expected
toEqual(expected)Values are deeply equal (see below)
toMatchObject(subset)actual contains every property in subset, recursively
TypeScript
TS
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.
  • Date by time, RegExp by source and flags, Map and Set by contents.
  • NaN equals NaN.
  • A key set to undefined still 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

MatcherPasses 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
TypeScript
TS
1import { NotFoundError } from '@axiljs/core'
2
3expect(err).toBeInstanceOf(NotFoundError)
4expect(user.deletedAt).toBeNull()

Numbers

MatcherPasses 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:

TypeScript
TS
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

MatcherPasses 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
TypeScript
TS
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.

TypeScript
TS
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.

expectedPasses when the thrown error
omittedis anything
stringhas a message that contains the string
RegExphas a message matching the pattern
an error classis an instance of the class
an Error instancehas exactly the same message
TypeScript
TS
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

TypeScript
TS
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.

MatcherPasses 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
TypeScript
TS
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:

TypeScript
TS
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}

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY