1

I have an interval set to run a function every 5 minutes: const timer = setInterval(func, TIMEOUT)

This starts when a specific object is created and I use clearInterval to stop it once a condition is met. This works as expected in practice. However, there are certain tests (using chai and sinon) that result in the creation of the object, though they are not specifically testing the creation of the object. This leads to the creation of the interval, which prevents the tests from every finishing.

I saw in node there is timer.unref(), which sounds like it would work for me, but in practice since setInverval in js returns an id, I get a type error Timer.unref is not a function

Is there a way to stop an interval in javascript when the test process ends?

Edit: The creation of the object exists in one package, as part of an API call, and the tests are calling the API from another package, so do not have access to the creation of the object nor the timer. The condition which clears the interval is not (and cannot) be met in the tests.

Meghan King
  • 185
  • 2
  • 3
  • 7
  • Does this answer your question? [Stop setInterval call in JavaScript](https://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript) – JHoffmann Sep 01 '21 at 23:47
  • 1
    TL;DR - use `clearInterval` – Bravo Sep 01 '21 at 23:49
  • monkey patch the creation of the object inside a function, where it creates the object and sets a globally reachable variable to the id of the timer. From there call clearInterval inside the tests. Without a concrete example, it is very difficult to understand what is going on. – ibrahim tanyalcin Sep 01 '21 at 23:53
  • you mentioned **However, there are certain tests (using chai and sinon) that result in the creation of the object**? if so, why not `clearInterval` inside each test case which will create related object? – Sphinx Sep 01 '21 at 23:53
  • 1
    "The creation of the object exists in one package, as part of an API call, and the tests are calling the API from another package, so do not have access to the creation of the object nor the timer. The condition which clears the interval is not (and cannot) be met in the tests." - sounds like your software isn't designed correctly. You should fix that instead of trying to work-around it. – Dai Sep 02 '21 at 00:08

0 Answers0