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

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

我有一些异步操作需要使用 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 不是假的,期望失败。

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

测试异步代码时,您需要return来自测试的承诺。将测试体改为:

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

This is the pattern facebook uses for testing async code with jest.

或者,您可以遵循 done 模式 as described here:

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

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

这是备用解决方案。

Jest 将在到达上下文末尾时终止。所以你需要return回调中的承诺告诉它等待承诺得到解决和测试。

假设有一个承诺

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

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

.resolves 等待 promise 解决,您应用适当的 matchers如你所愿。

您还可以在检查错误情况时使用 .rejects