简体   繁体   中英

How can I test this function with Jest?

I'm trying to unit test a typewriter function but the value received is undefined no matter what I do.

I've looked at the Jest docs and I've also tried async with no luck.

let speed = 120;

  function typeWriter(id, text) {
    return function () {
      if (text) {
        document.getElementById(id).innerHTML += text[0];
        setTimeout(typeWriter(id, text.slice(1)), speed);
      }
    };
  }
typeWriter("job-title", "Web Developer")();

I'm expecting the innerHTML value of the element with an id of job-title to be Web Developer instead of undefined.

You'll need to use Jest Timer Mocks like this:

let speed = 120;

function typeWriter(id, text) {
  return function () {
    if (text) {
      document.getElementById(id).innerHTML += text[0];
      setTimeout(typeWriter(id, text.slice(1)), speed);
    }
  };
}

describe('typeWriter', () => {
  beforeEach(() => { jest.useFakeTimers(); });
  afterEach(() => { jest.useRealTimers(); });

  it('should work', () => {
    document.body.innerHTML = '<div><span id="job-title"></span></div>';
    const text = "Web Developer";

    typeWriter("job-title", text)();

    for (let i = 1; i <= text.length; i++) {
      expect(document.getElementById('job-title').innerHTML).toBe(text.substring(0, i));
      jest.advanceTimersByTime(speed);
    }
  });
});

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