当测试下面的功能时,我似乎无法使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);
});