7

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.

Ace shinigami
  • 1,374
  • 2
  • 12
  • 25

1 Answers1

2

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.

Edit Track the test case status in jest

Community
  • 1
  • 1
Sohail Ashraf
  • 10,078
  • 2
  • 26
  • 42