To mock or spy on setInterval
in a unit test using Chai and Sinon, we can use the fake
method provided by Sinon.
Let's assume we want to test a module that contains a function which invokes setInterval
and we want to mock setInterval
to ensure that our test runs faster, we can do as follows:
index.ts592 chars27 lines
In the before and after each hooks, we use Sinon's useFakeTimers
and restore
methods to create and restore a clock object, which will replace the real setInterval
with a fake one.
Then, in the it
block, we stub setInterval
with Sinon's stub
method and pass a fake implementation using callsFake
method which will be invoked every time setInterval
is called.
Finally, we invoke the function to be tested and use Chai's expect
assertion to verify if setInterval
was called once.
This way, the test will not hold because we've mocked time-consuming method in our test.
gistlibby LogSnag