美文网首页
10|mock timers的使用

10|mock timers的使用

作者: 雪燃归来 | 来源:发表于2020-05-24 15:17 被阅读0次

    一、mock timers的使用

    // timer.js
    export const timer = (callback) => {
        setTimeout(() => {
            callback()
        },3000)
    }
    
    // timer.test.js
    import { timer } from './timer'
    jest.useFakeTimers();
    test('timer 测试', () => {
        const fn = jest.fn();
        timer(fn);
        jest.runAllTimers();
        expect(fn).toHaveBeenCalledTimes(1);
    })
    

    二、runOnlyPendingTimers 运行只处于队列中任务

    //timer
    export const timer = (callback) => {
        setTimeout(() => {
            callback()
            setTimeout(() => {
                callback()
            })
        },3000)
    }
    
    //timer.test.js
    import { timer } from './timer'
    jest.useFakeTimers();
    test('timer 测试', () => {
        const fn = jest.fn();
        timer(fn);
        jest.runOnlyPendingTimers();
        expect(fn).toHaveBeenCalledTimes(1);
    })
    

    三、advanceTimersByTime 时间快进

    // timer.js
    export const timer = (callback) => {
        setTimeout(() => {
            callback()
            setTimeout(() => {
                callback()
            },3000)
        },3000)
    }
    
    // timer.test.js
    import { timer } from './timer'
    jest.useFakeTimers();
    test('timer 测试', () => {
        const fn = jest.fn();
        timer(fn);
        jest.advanceTimersByTime(3000);
        expect(fn).toHaveBeenCalledTimes(1);
    })
    

    四、排除各测试之间的干扰

    import { timer } from './timer'
    beforeEach(() => {
        jest.useFakeTimers()
    })
    test('timer 测试', () => {
        const fn = jest.fn();
        timer(fn);
        jest.advanceTimersByTime(3000);
        expect(fn).toHaveBeenCalledTimes(1);
        jest.advanceTimersByTime(3000);
        expect(fn).toHaveBeenCalledTimes(2);
    })
    
    test('timer1 测试', () => {
        const fn = jest.fn();
        timer(fn);
        jest.advanceTimersByTime(3000);
        expect(fn).toHaveBeenCalledTimes(1);
        jest.advanceTimersByTime(3000);
        expect(fn).toHaveBeenCalledTimes(2);
    })
    

    相关文章

      网友评论

          本文标题:10|mock timers的使用

          本文链接:https://www.haomeiwen.com/subject/nlqjahtx.html