繁体   English   中英

为什么我的异步 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 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模式done

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

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

这是替代解决方案。

一旦到达上下文结束,Jest 将被终止。 所以你需要从回调中返回承诺,告诉它等待承诺得到解决和测试。

让我们说有一个承诺

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

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

.resolves等待promise解决,您可以根据需要应用适当的matchers

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

暂无
暂无

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

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