Chris
Chris

Reputation: 85

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.

Upvotes: 2

Views: 138

Answers (1)

Brian Adams
Brian Adams

Reputation: 45780

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

Upvotes: 1

Related Questions