admin管理员组

文章数量:1355655

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

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

Share Improve this question asked Jun 15, 2018 at 22:43 TakuhiiTakuhii 9672 gold badges9 silver badges29 bronze badges 1
  • Possible duplicate of How jasmine clock works? – mooga Commented Jun 15, 2018 at 22:50
Add a ment  | 

2 Answers 2

Reset to default 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();
});

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!

本文标签: javascriptCan I test setInterval with JasmineStack Overflow