I’m trying to understand how asynchronous testing works in Jest.
What I’m trying to do is similar to an example from the Jest documentation. This works fine ..
JavaScript
x
20
20
1
function doAsync(c) {
2
c(true)
3
}
4
5
test('doAsync calls both callbacks', () => {
6
7
expect.assertions(2);
8
9
function callback1(data) {
10
expect(data).toBeTruthy();
11
}
12
13
function callback2(data) {
14
expect(data).toBeTruthy();
15
}
16
17
doAsync(callback1);
18
doAsync(callback2);
19
});
20
But I want to delay the callback invocations so I tried this ….
JavaScript
1
7
1
function doAsync(c) {
2
setTimeout(() => {
3
console.log('timeout fired')
4
c(true)
5
}, 1000)
6
}
7
but the test fails with the message Expected two assertions to be called but received zero assertion calls.
.
The log message ‘timeout fired’ doesn’t appear in the console.
Please can someone explain why it fails?
Advertisement
Answer
You need to use jest’s timer mocks https://jestjs.io/docs/en/timer-mocks
First you tell jest to use mock timers, then you run the timers within your test.
It would look something like:
JavaScript
1
26
26
1
function doAsync(c) {
2
setTimeout(() => {
3
c(true)
4
}, 1000)
5
}
6
7
jest.useFakeTimers()
8
9
test('doAsync calls both callbacks', () => {
10
11
expect.assertions(2);
12
13
function callback1(data) {
14
expect(data).toBeTruthy();
15
}
16
17
function callback2(data) {
18
expect(data).toBeTruthy();
19
}
20
21
doAsync(callback1);
22
doAsync(callback2);
23
24
jest.runAllTimers(); // or jest.advanceTimersByTime(1000)
25
});
26