【问题标题】:How to mock timer with Jest in React如何在 React 中使用 Jest 模拟计时器
【发布时间】:2020-09-16 01:59:26
【问题描述】:

我无法测试我的功能,因为我中间有一个计时器。我如何用 Jest 模拟计时器

"await new Promise(resolve => setTimeout(resolve, 1000))"

async callAPI(user) {
   await new Promise(resolve => setTimeout(resolve, 1000));
   //Code.....
   try{
   .....
    }catch (error) {

   }
}

【问题讨论】:

标签: reactjs jestjs


【解决方案1】:

如果你想等待1秒,你可以用jest fake timers


jest.useFakeTimers();

it('test something after 1sec', () => {


  // Wait for 1 sec
  jest.advanceTimersByTime(1000);

  ...
});

【讨论】:

    猜你喜欢
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    • 2018-01-26
    • 2017-08-17
    • 2023-04-02
    相关资源
    最近更新 更多