简体   繁体   中英

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM