无法在Jest中模拟setTimeout,结果返回未定义

时间:2019-09-09 15:33:49

标签: javascript unit-testing jestjs

我有一个具有setTimeout的函数sum,我想使用Jest测试此函数,但是我不确定如何模拟setTimeout,因此它不会延迟100000 ms组。我曾经使用过jest.useFakeTimers();jest.runOnlyPendingTimers();,但没有运气来进行测试,有人可以建议我修复并提高我的模拟知识吗?

错误: Comparing two different types of values. Expected number but received undefined.

JS

function sum(x, y) {
  let start;

  setTimeout(() => {
    start = x + y;
    return start;
  }, 100000);
}

规范

describe('Utility: Sum', () => {
  beforeEach(() => {
    jest.useFakeTimers();
  });
  afterEach(() => {
    jest.useRealTimers();
  });
  it('should return 2', () => {
    const result = sum(1, 1);
    expect(result).toEqual(2);
    jest.runOnlyPendingTimers();
  });
});

1 个答案:

答案 0 :(得分:0)

您的函数sum将始终返回undefined

结帐es6 promisehow to use async in jest

将功能更改为:

async function sum(x, y) {
  return new Promise(resolve =>{
  setTimeout(() => {
    resolve(x+y);
  }, 100000)})
}