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.

1 answer

  • answered 2019-04-15 06:28 brian-lives-outdoors

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