玩笑测试setTimeout的行为不符合预期

时间:2018-11-19 19:37:07

标签: javascript html5 unit-testing jestjs

当测试下面的功能时,我似乎无法使setTimeout正常工作。 我尝试按照文档中的建议使用useakeTimers,runAllTimers,advanceTimersByTime,但计时器似乎根本没有激活。

const clearTasks = () => {
  const clearTasksBtn = document.querySelector('.clear-tasks-btn');
  const tasksSection = document.querySelector('.tasks-section');
  const body = document.body;
  clearTasksBtn.addEventListener('click', e => {
    if (tasksSection.childElementCount) {
      Array.from(tasksSection.children).forEach(child => child.remove());
      localStorage.clear();
    } else {
      if (body.firstChild.className === 'alert') {
      } else {
        const alert = document.createElement('p');
        alert.className = 'alert';
        alert.textContent = "There aren't any tasks";
        body.insertBefore(alert, body.childNodes[0]);
        setTimeout(() => {
          alert.remove();
        }, 2000);
      }
    }
  });
};
我的测试

import clearTasks from './clearTasks';
describe('clearTasks', () => {
  document.body.innerHTML = `
    <button  class="clear-tasks-btn">Clear Tasks</button>
    <section class="tasks-section"></section>
    `;
  const body = document.body;
  const clearTasksBtn = document.querySelector('.clear-tasks-btn');
    beforeEach(() => {
        clearTasks();
        clearTasksBtn.click();
        jest.useFakeTimers()
        jest.runAllTimers()
        jest.advanceTimersByTime(2000)
    });
  it("should display alert if section with class tasks-section dosn't have any children", () => {
    
    expect(body.firstChild.className).toMatch('alert');
  });
  it('should remove the alert after 2000 milliseconds', () => {
    expect(body.firstChild.className).not.toMatch('alert');
  },2000);
});

0 个答案:

没有答案