We have been using useFakeTimers()
(sinon v11.x) in many spec files for quite a long time. Recently, we have updated our sinon to 14.x version, now the tests are failing with below error.
TypeError: Can't install fake timers twice on the same global object.
We have tried with createSandbox()
also, didn't help.
We have been using useFakeTimers()
(sinon v11.x) in many spec files for quite a long time. Recently, we have updated our sinon to 14.x version, now the tests are failing with below error.
TypeError: Can't install fake timers twice on the same global object.
We have tried with createSandbox()
also, didn't help.
- Please provide a mvce – Lin Du Commented Aug 4, 2022 at 9:29
3 Answers
Reset to default 4The issue seems like after Sinon 12.x, not restoring the clock in the spec files, injecting it into global scope which throws the aforementioned error.
So the fix is, call clock.restore()
in afterAll()
or afterEach()
based on whether you used beforeAll()
or beforeEach()
.
So, I encountered this error, for instance, if I had two tests which both used fake timers. You have to call useFakeTimers independently of your sandbox creation.
Fails miserably because reasons
/// Somefile
const superTrialAndErrorSimulator = sinon.createSandbox({
useFakeTimers: true
});
// Some other file
const superTrialAndErrorSimulatorZool = sinon.createSandbox({
useFakeTimers: true
});
If you set fake timers after setting the sandbox, then reset them, it works. Wele to the trial and error world of sinon.
Works miserably because reasons
const ifOnlyThereWereABetterLibrary = sinon.createSandbox();
before(() => {
ifOnlyThereWereABetterLibrary.useFakeTimers();
});
after(() => {
ifOnlyThereWereABetterLibrary.clock.restore();
});
// Works.
While Sinon's fake timers documentation page doesn't mention it, there is a clock.reset()
method mentioned in the GitHub README file. It resets the fake clock to the originally-set value.
FWIW: I first saw this in the tiny sinon-timers-repeatable library.