简体   繁体   English

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

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

I have some asynchronous actions that I need to test with Jest.我有一些需要用 Jest 测试的异步操作。 My test is currently passing when it should fail.我的测试目前正在通过,但它应该失败。

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

When I run npm test , I get the following output:当我运行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

As you can see, the test is passing, but console.log(3) is never executed because true is not falsy, and the expectation fails.如您所见,测试通过了,但是console.log(3)永远不会执行,因为true不是假的,并且期望失败。

How can I get Jest to recognize my expectations inside async callbacks?如何让 Jest 在异步回调中识别我的期望?

When testing asynchronous code, you need to return the promise from the test.测试异步代码时,您需要从测试中返回承诺。 Change the test body to:将测试主体更改为:

return someFunctionThatReturnsAPromise()
  .then(() => {
    expect(true).toBeFalsy();
  });

With that, the test fails as expected:这样,测试按预期失败:

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. 这是 facebook 使用 jest 测试异步代码的模式。

Alternatively, you can follow the done pattern as described here :或者,您可以按照此处所述的done模式done

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

This will work with Jest, but is more commonly used with Jasmine and Mocha.这将适用于 Jest,但更常用于 Jasmine 和 Mocha。

Here is the alternate solution.这是替代解决方案。

Jest will be terminated once it reaches the end of context.一旦到达上下文结束,Jest 将被终止。 So you need to return the promise from the callback to tell it to wait for the promise to get resolved and tested.所以你需要从回调中返回承诺,告诉它等待承诺得到解决和测试。

Lets say there is a promise让我们说有一个承诺

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

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

.resolves waits for the promise to resolve, and you apply appropriate matchers as your wish. .resolves等待promise解决,您可以根据需要应用适当的matchers

And also you can use .rejects when you are checking for the error cases.您也可以在检查错误情况时使用.rejects

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM