Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if test failed in 'afterEach' of Jest without jasmine

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.

like image 636
Ace shinigami Avatar asked Nov 16 '22 17:11

Ace shinigami


1 Answers

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

like image 185
Sohail Ashraf Avatar answered May 23 '23 20:05

Sohail Ashraf