Testing

Mocks and Spies

Create mock functions with fn(), spy on methods with spyOn(), stub return values and promises, and assert calls with toHaveBeenCalledWith in @axiljs/testing.

3 min readUpdated DocumentationEdit this page
On this page8

@axiljs/testing includes Jest-style mock functions with no extra dependency. fn() creates a standalone mock, spyOn() replaces a method on an object, and four matchers assert how they were called.

TypeScript
TS
1import { describe, it, expect, fn } from '@axiljs/testing'
2
3describe('notify', () => {
4  it('sends one email per user', async () => {
5    const send = fn().mockResolvedValue({ id: 'msg_1' })
6
7    await notify([{ email: 'a@x.dev' }, { email: 'b@x.dev' }], send)
8
9    expect(send).toHaveBeenCalledTimes(2)
10    expect(send).toHaveBeenLastCalledWith('b@x.dev', 'Welcome')
11  })
12})

fn(implementation?)

Returns a callable mock. Without an implementation it returns undefined.

TypeScript
TS
const add = fn((a: number, b: number) => a + b)
add(1, 2)          // 3
add.mock.calls     // [[1, 2]]

spyOn(object, method)

Replaces object[method] with a mock that calls through to the original until you change its behaviour. mockRestore() puts the original back.

TypeScript
TS
1import { spyOn } from '@axiljs/testing'
2
3const log = spyOn(console, 'log').mockImplementation(() => {})
4
5runJob()
6expect(log).toHaveBeenCalled()
7
8log.mockRestore()

spyOn throws a TypeError if the property is not a function. Spying on a method that is already a mock returns that mock.

Configuring behaviour

All configuration methods return the mock, so they chain.

MethodEffect
mockImplementation(f)Use f for every call
mockImplementationOnce(f)Use f for the next call only (queued, first in first out)
mockReturnValue(v) / mockReturnValueOnce(v)Return v
mockResolvedValue(v) / mockResolvedValueOnce(v)Return Promise.resolve(v)
mockRejectedValue(e) / mockRejectedValueOnce(e)Return Promise.reject(e)
mockName(name) / getMockName()Label the mock (default 'mock')

"Once" values are used before the default implementation:

TypeScript
TS
1const fetchRate = fn()
2  .mockResolvedValueOnce(1.08)
3  .mockRejectedValueOnce(new Error('timeout'))
4  .mockResolvedValue(1.1)
5
6await fetchRate() // 1.08
7await fetchRate() // throws 'timeout'
8await fetchRate() // 1.1, and every call after

Inspecting calls: mock

PropertyContents
mock.callsArguments of every call, in order
mock.results{ type: 'return' | 'throw', value } for every call
mock.instancesthis of every call
mock.lastCallArguments of the most recent call, or undefined

Resetting

MethodClears recorded callsClears implementationsRestores original
mockClear()yesnono
mockReset()yesyesno
mockRestore()yesyesyes, for spies

mockReset() on a spy keeps calling through to the original method.

Matchers

MatcherPasses when
toHaveBeenCalled()Called at least once
toHaveBeenCalledTimes(n)Called exactly n times
toHaveBeenCalledWith(...args)Any call had these arguments (deep equality)
toHaveBeenLastCalledWith(...args)The last call had these arguments

All of them support .not. Use isMockFunction(value) to check whether a value is a mock.

Mocking a service in a route test

TypeScript
TS
1import { describe, it, expect, spyOn, createTestClient } from '@axiljs/testing'
2import { app } from '../src/app'
3import { mailer } from '../src/services/mailer'
4
5describe('POST /signup', () => {
6  it('sends a welcome email', async () => {
7    const send = spyOn(mailer, 'send').mockResolvedValue(undefined)
8    const client = createTestClient(app)
9
10    const res = await client.post('/signup').send({ email: 'new@x.dev' })
11
12    expect(res.status).toBe(201)
13    expect(send).toHaveBeenCalledWith('new@x.dev', 'Welcome')
14    send.mockRestore()
15  })
16})

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY