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.
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.
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.
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.
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.
| Method | Effect |
|---|---|
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:
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 afterInspecting calls: mock
| Property | Contents |
|---|---|
mock.calls | Arguments of every call, in order |
mock.results | { type: 'return' | 'throw', value } for every call |
mock.instances | this of every call |
mock.lastCall | Arguments of the most recent call, or undefined |
Resetting
| Method | Clears recorded calls | Clears implementations | Restores original |
|---|---|---|---|
mockClear() | yes | no | no |
mockReset() | yes | yes | no |
mockRestore() | yes | yes | yes, for spies |
mockReset() on a spy keeps calling through to the original method.
Matchers
| Matcher | Passes 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
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})Related
Was this page helpful?