When one of my Jest tests fails I want to store a screenshot, but only when it fails.
Here is a piece of my test code as an example, the !passed
part in the afterEach is not working.
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');
});
afterEach(async () => {
if (!passed) takeScreenshot();
await driver.quit();
});
});
With jasmine I would do something like:
var passed = jasmine.getEnv().currentSpec.results().passed();
But I cannot find something similar for Jest. Maybe there is another solution like taking a screenshot on each failing expect? I tried a try/catch around the expect, but then the test always passes...
How can I check with Jest if my test failed in the afterEach?
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');
});
});