最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sinon: Can't install fake timers twice on the same global object - Stack Overflow

programmeradmin0浏览0评论

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.

Share Improve this question asked Aug 4, 2022 at 8:54 Kamalakannan JKamalakannan J 2,9983 gold badges26 silver badges56 bronze badges 1
  • Please provide a mvce – Lin Du Commented Aug 4, 2022 at 9:29
Add a ment  | 

3 Answers 3

Reset to default 4

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

发布评论

评论列表(0)

  1. 暂无评论