【问题标题】:Why is my async Jest test not failing when it should?为什么我的异步 Jest 测试在应该失败的时候没有失败?
【发布时间】:2016-10-31 19:53:10
【问题描述】:

我有一些异步操作需要用 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 识别我在异步回调中的期望?

【问题讨论】:

    标签: javascript asynchronous es6-promise jestjs


    【解决方案1】:

    在测试异步代码时,您需要从测试中返回 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
    

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

    【讨论】:

    • 有没有办法在 Jest 中通过一个测试来测试多个这样的 Promise,或者我必须对每个 Promise 进行一次测试? (在这种情况下异步/等待不起作用)
    • @Sergej 这取决于几个不同的事情。如果你想验证 Promise 之间的关系,你可以use Promise.all。但是,如果它们不同,您可能希望它们在单独的测试中。
    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      这是替代解决方案。

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

      假设有一个承诺

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

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-12-04
        • 2021-02-27
        • 2022-10-18
        • 1970-01-01
        • 1970-01-01
        • 2018-04-06
        • 1970-01-01
        相关资源
        最近更新 更多