Skip to content
Advertisement

Can I test setInterval with Jasmine?

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

Advertisement

Answer

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();
});
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement