使用jest测试setTimout

nle07wnf  于 8个月前  发布在  Jest
关注(0)|答案(1)|浏览(88)

我试图测试一个函数,提醒用户,然后关闭后3000.我得到的类仍然存在后,超时功能已被调用.我使用引导警报,我想知道如果我是正确的测试?
测试代码:

setTimeout(function () {
        let messages = document.getElementById("msg");
        let alert = new bootstrap.Alert(messages);
        alert.close();
    }, 3000);

字符串
script.test.js:

jest.useFakeTimers();
describe("Timer alerts and then closes after 3000", () => {

    beforeAll(() => {
        let fs = require("fs");
        let fileContents = fs.readFileSync("templates/base.html", "utf-8");
        document.open();
        document.write(fileContents);
        document.close();
    });

    test('closes the alert after 3 second via advanceTimersByTime', () => {
        const element = document.getElementById("msg");
        expect(element).not.toBeNull();

        require('../script');

        expect(document.querySelector('.alert')).toBeTruthy();
        jest.runAllTimers();
        jest.advanceTimersByTime(3000);
        expect(document.querySelector('.alert')).toBeNull();

    });
});

hl0ma9xz

hl0ma9xz1#

我看到不同的细节检查:
1-在官方文档中,说需要在global.setTimeout中添加spy。在jest.useFakeTimers();之后添加jest.spyOn(global, 'setTimeout');
2-运行脚本,添加const script = require('../script'); script()来运行它
3-检查是否调用了setQuery,添加expect(setTimeout).toHaveBeenCalledTimes(1);expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 1000);
官方文档:jest timer-mocks

相关问题