Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
198
rated 0 times [  200] [ 2]  / answers: 1 / hits: 49411  / 6 Years ago, wed, october 3, 2018, 12:00:00

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



function doAsync(c) {
c(true)
}

test('doAsync calls both callbacks', () => {

expect.assertions(2);

function callback1(data) {
expect(data).toBeTruthy();
}

function callback2(data) {
expect(data).toBeTruthy();
}

doAsync(callback1);
doAsync(callback2);
});


But I want to delay the callback invocations so I tried this ....



 function doAsync(c) {
setTimeout(() => {
console.log('timeout fired')
c(true)
}, 1000)
}


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?


More From » jestjs

 Answers
4

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:



function doAsync(c) {
setTimeout(() => {
c(true)
}, 1000)
}

jest.useFakeTimers()

test('doAsync calls both callbacks', () => {

expect.assertions(2);

function callback1(data) {
expect(data).toBeTruthy();
}

function callback2(data) {
expect(data).toBeTruthy();
}

doAsync(callback1);
doAsync(callback2);

jest.runAllTimers(); // or jest.advanceTimersByTime(1000)
});

[#53381] Friday, September 28, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daquanmilesw

Total Points: 57
Total Questions: 102
Total Answers: 110

Location: Wallis and Futuna
Member since Sat, Aug 6, 2022
2 Years ago
daquanmilesw questions
;