为什么我的异步Jest测试在应该失败的时候没有失败

Why is my async Jest test not failing when it should?

本文关键字:失败 候没 异步 我的 Jest 测试 为什么      更新时间:2023-09-26

我有一些异步操作需要用Jest进行测试。我的测试本应失败,但现在却通过了。

describe('Asynchronous Code', () => {
  it('should execute promise', () => {
    console.log(1);
    someFunctionThatReturnsAPromise()
      .then(() => {
        console.log(2);
        expect(true).toBeFalsy();
        console.log(3);
      });
    console.log(4);
  });
});

当我运行npm test时,我得到以下输出:

PASS  __tests__/Async.test.js
 ● Console
   console.log __tests__/Async.test.js:3
     1
   console.log static-content-test/react/actions/DashboardActions.test.js:6
     2
   console.log static-content-test/react/actions/DashboardActions.test.js:10
     4

正如您所看到的,测试正在通过,但console.log(3)从未被执行,因为true不是falsy,并且期望失败。

如何让Jest在异步回调中识别我的期望?

测试异步代码时,需要从测试中返回promise。将测试体更改为:
return someFunctionThatReturnsAPromise()
  .then(() => {
    expect(true).toBeFalsy();
  });

这样,测试就如预期的那样失败了:

FAIL  __tests__/Async.test.js
 ● Asynchronous Code › should execute promise
   expect(received).toBeFalsy()
   Expected value to be falsy, instead received
     true

这是facebook使用jest测试异步代码的模式。

或者,您可以按照这里描述的done模式:

it('should execute promise', (done) => {
  someFunctionThatReturnsAPromise()
    .then(() => {
      expect(true).toBeFalsy();
      done();
    });
});

这将适用于Jest,但更常用于Jasmine和Mocha。

这是另一种解决方案。

一旦到达上下文末尾,Jest将被终止。因此,您需要从回调返回promise,告诉它等待promise得到解决和测试。

假设有一个承诺

const promise=fetch("blah.com/api")

test("should return valid data",()=>{
   return expect(promise).resolves.toBeTruthy() 
})

.resolves等待promise解析,然后应用适当的matchers如您所愿。

在检查错误情况时,也可以使用.rejects