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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With