【问题标题】:Jest Test Scheduler methodJest Test Scheduler 方法
【发布时间】:2020-12-03 03:36:52
【问题描述】:

我有一个运行调度程序的简单类。

类似这样的:

export class ExportScheduler {
    constructor(cron: string, private product: Product) {
        cron.schedule(cron, () => this.export());
    }

    async export(): Promise<any> {
        const access = new Accessor(this.product);

        return access.calc();
    }
}

我想使用 Jest 编写一个测试,它基本上测试调度程序。

beforeEach(() => {
    clock = sinon.useFakeTimers();
    cut = new ExportScheduler(
       '* * * * *',
        product
    );
   });

it('should schedule exports', async () => {
    expect(await cut.export).not.toHaveBeenCalled();
    clock.tick(70000);
    expect(await cut.export).toHaveBeenCalledTimes(1);
}

但它告诉我以下内容:

匹配器错误:接收到的值必须是模拟或间谍函数

我应该如何测试这个调度器。

【问题讨论】:

    标签: javascript typescript express testing jestjs


    【解决方案1】:

    您应该在这里使用jest 全局对象。

    模拟 CRON 计时器

    监视类方法

    let cut
    
    beforeEach(() => {
        jest.useFakeTimers('modern')
    
        cut = new ExportScheduler('* * * * *', product);
    });
    
    afterEach(() => {
        jest.clearAllTimers();
    })
    
    it('does not invoke .export(), before 60 seconds have passed', () => {
        const exportSpy = jest.spyOn(cut, 'export');
    
        jest.advanceTimersByTime(50000);
    
        expect(exportSpy).not.toBeCalled();
    }
    
    it('invokes .export() once, after 60 seconds have passed', () => {
        const exportSpy = jest.spyOn(cut, 'export');
    
        jest.advanceTimersByTime(60000);
    
        expect(exportSpy).toHaveBeenCalledTimes(1);
    }
    

    请注意,您实际上并不需要使用异步,因为您只是断言该方法已被调用。在此示例中,如果您计划断言 .export() 的已解决承诺的值,您只想使测试异步。

    【讨论】:

      猜你喜欢
      • 2018-08-29
      • 2022-01-18
      • 2019-06-09
      • 1970-01-01
      • 1970-01-01
      • 2019-02-10
      • 2019-01-25
      • 1970-01-01
      • 2020-11-26
      相关资源
      最近更新 更多