javascript - 我如何用 Jest 测试这个功能?

标签 javascript unit-testing jestjs

我正在尝试对打字机功能进行单元测试,但无论我做什么,收到的值都是未定义的。

我看过 Jest 文档,也尝试过异步,但没有成功。

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

我希望 id 为 job-title 的元素的 innerHTML 值是 Web Developer 而不是 undefined。

最佳答案

你需要使用Jest Timer Mocks像这样:

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

关于javascript - 我如何用 Jest 测试这个功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55683250/

相关文章:

javascript - 提交前检查 Javascript 中的多个函数是否为真

javascript - 如何使用 jQuery 添加一个 div 作为倒数第二个 div?

c++ - 具有依赖于时钟时间的私有(private)成员的方法的 GTest

c# - 在 ASP.NET MVC 单元测试中使用 Activator.CreateInstance(...)

php - 为执行 exec() 的对象创建测试

javascript - 将数据放入html5 data-* 中是否正确?

javascript - 从数组中删除多个元素

javascript - 开 Jest : Error when trying to import Native Modules; unable to prevent with Mock

reactjs - 使用 Jest 和 enzyme 进行 native 单元测试时出现 TypeError : Cannot read property 'getParam' of undefined.?

javascript - 在 vue 中使用 jest 时编译失败但测试用例通过