Check if test failed in afterEach of Jest
Here is an example how I solved it in my project: (Assuming that afterEach is used only for taking screenshots and not for cleanup and other navigates)
const testIt = (name, action) => {
test(name, async () => {
try {
await action()}
catch (error) {
await screenshots.createScreenshot(page) //take screenshot
throw error
}
})
}
describe('Test scenario 1', () => {
testIt('test1 will Pass', async () => {
expect(true).toBe(true)
})
testIt('test2 will Fail', async () => {
expect(true).toBe(false)
})
afterEach(async () => {
//ignored
})
})
I use jest-html-reporters, and only failed tests will have attachment there (this solution did not require any other configurations). Result:
- test1 - passed, no screenshot
- test2 - failed, has screenshot
Seems the jasmine object can be used in Jest tests, but the currentSpec has been removed in the 2.x version.
I have found an alternative with the use of jasmine custom reports. Just make sure you also move the driver.quit()
to the reporter as you might still need the driver after the test.
Here is an simple example for the reporter handling failing tests at the end of the test:
const reporter = {
specDone: async (result) => {
if (result.status === 'failed') {
takeScreenshot(result.description);
}
await driver.quit();
},
};
jasmine.getEnv().addReporter(reporter);
describe('Page', () => {
it('should contain Text in the header', async () => {
// Arrange
const page = new Page(driver);
// Act
await page.open();
// Assert
expect(await page.getHeaderText()).toBe('Something');
});
});
Store current spec results in Jasmine and access it in afterEach
.
@Niels van Reijmersdal is on the right track. However, the downside of taking a screenshot in specDone
is that it runs after afterEach
, so if there's something in afterEach
that, say, navigates back a few screens, the screenshot you end up taking won't be representative of where the error took place. Here's an answer that allows you to take a screenshot immediately after the error occurs.
Add a custom Jasmine reporter for
specStarted
and store the spec results tojasmine.currentTest
.jasmine.getEnv().addReporter( { specStarted: result => jasmine.currentTest = result } );
The unintuitive thing about this is that even though we're storing this in
specStarted
before the results are in,jasmine.currentTest
stores a reference to theresult
object which will get updated dynamically as the spec runs so when we access it in ourafterEach
, it will be holding the results of the spec properly.Check for
failedExpectations
in yourafterEach
and take a screenshot if there's been any failures.afterEach( async () => { if ( jasmine.currentTest.failedExpectations.length > 0 ) { // There has been a failure. await driver.takeScreenshot(); } } );