检查没有茉莉花的 Jest 的“afterEach"中的测试是否失败 [英] Check if test failed in 'afterEach' of Jest without jasmine

查看:17
本文介绍了检查没有茉莉花的 Jest 的“afterEach"中的测试是否失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够检查我的 Jest 测试是成功还是失败.还有

I want to be able to check whether one my Jest tests succeeded or failed. There is another SO question on this topic, but the solution uses Jasmine, is kind hacky, and is by no means guaranteed to continue working with future versions of Jasmine or Jest. I'm looking for a solution to this problem which doesn't tack on a large dependency like Jasmine.

解决方案

You could track the test status by creating a flag in the test suite.

Explanation.

Create a flag testStatus in the describe block and two counter variables ( if you want to get the count of the Failed and passed test cases). And set the initial value of the flag testStatus to false.

describe("Should count the test", () => {
  let testStatus = false;
  let passTests = 0;
  let failedTest = 0;

  //.... test cases

});

And in each test case at the end of the test case set the value of the flag testStatus to true.

it("Should fail/Pass", () => {
    expect(false).toBe(true);
    testStatus = true;
});

The line after expect will only run if the test cases executed successfully, Otherwise the flag value will remain false.

And now in afterEach we can check if the flag value (testStatus) is true or false.

if the value is false then the test case got failed and if the value is true means test case executed successfully.

And reset the value of the flag (testStatus) back to false.

afterEach(() => {
    if (testStatus) {
      passTests += 1;
    } else {
      failedTest += 1;
    }

    testStatus = false;
});

Hope this will be helpful.

Live example.

这篇关于检查没有茉莉花的 Jest 的“afterEach"中的测试是否失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆