为什么我的异步Jest测试没有失败呢?

Luk*_*uke 3 javascript asynchronous es6-promise jestjs

我有一些我需要用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);
  });
});
Run Code Online (Sandbox Code Playgroud)

当我运行时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
Run Code Online (Sandbox Code Playgroud)

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

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

Luk*_*uke 9

在测试异步代码时,您需要从测试中返回promise.将测试体更改为:

return someFunctionThatReturnsAPromise()
  .then(() => {
    expect(true).toBeFalsy();
  });
Run Code Online (Sandbox Code Playgroud)

有了这个,测试失败了:

FAIL  __tests__/Async.test.js
 ? Asynchronous Code › should execute promise

   expect(received).toBeFalsy()

   Expected value to be falsy, instead received
     true
Run Code Online (Sandbox Code Playgroud)

这是facebook用于通过jest测试异步代码的模式.