Skip to content
Advertisement

Jest unit test: setTimeout not firing in async test

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

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

JavaScript

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
Advertisement