3

I have this statement in my code, and I was wondering how I could test the setInterval using Jasmine.

const x = setInterval(() => {
    const countdown = getElementById('countdownWrapper');
    const systemTime = ...
    const now = new Date().getTime();
    const endTime = systemTime - now;

    countdown.querySelector('.countdown-time').innerHTML = time();

    if (endTime < 0) {
        clearInterval(x);
        countdown.classList.remove('countdown-time--show');
    }
}, 1000);

systemTime is fed from an epoch value in a DATA-CONTENT attribute in the HTML.

Any help would be greatly appreciated

Takuhii
  • 819
  • 2
  • 8
  • 26
  • Possible duplicate of [How jasmine clock works?](https://stackoverflow.com/questions/28889562/how-jasmine-clock-works) – mooga Jun 15 '18 at 22:50

2 Answers2

6
beforeEach(function() {
  timerCallback = jasmine.createSpyObj("setInterval");
  jasmine.clock().install();
});

afterEach(function() {
  jasmine.clock().uninstall();
});

it("causes a timeout to be called", function() {
  setTimeout(function() {
    timerCallback();
  }, 1000);

  expect(setInterval).not.toHaveBeenCalled();

  jasmine.clock().tick(1001);

  expect(setInterval).toHaveBeenCalled();
});
Benny Code
  • 51,456
  • 28
  • 233
  • 198
mooga
  • 3,136
  • 4
  • 23
  • 38
  • Where would I call the code I am testing, as I have tried it in the beforeEach before the SpyOn, I have also created `let timerCallback` before the beforeEach, but I am still getting `createSpyObj requires a non-empty array or object of method names to create spies for thrown. Error: : Expected a spy, but got undefined.` This sounds like the function isn't firing – Takuhii Jun 16 '18 at 06:50
  • Fantastic, thanks for the help, but at which point do I call my script to test? I've placed it in the beforeEach, but I am getting this error `createSpyObj requires a non-empty array or object of method names to create spies for thrown Error: : Expected a spy, but got Function. Usage: expect().toHaveBeenCalled()` – Takuhii Jun 16 '18 at 17:20
  • I am using Headless Chrome to run the unit tests, would that make a difference? – Takuhii Jun 17 '18 at 08:36
0

Correction to Benny's answer:

timerCallback = jasmine.createSpyObj("test", {setInterval: 0});
AND
expect(timerCallback.setInterval).not.toHaveBeenCalled();

Also, this DOESN'T test setInterval, that's been mocked here. This tests setTimeout!