I have a test suite running using Jest. I would like to trigger a hook after any failed test, ideally with the context of the test still available.
Specifically, I am using Puppeteer via jest-puppeteer. The goal is to take a screenshot of the page after a test failure, before the page is closed in the tearDown function.
What's the best way to achieve that?
An example of my test suite:
describe('My tests', () => {
beforeAll(async () => {
await page.goto('http://example.com');
});
// TODO I need something like this
onFailure(async (something) => {
page.takeScrenshot();
});
test('My example test', async () => {
return await page.waitFor('.example-selector');
});
});
I have found that there is onTestFailure option when setting up a test-runner, is it possible to leverage that?
Jest does not have a built-in onFailure hook, but you can achieve similar functionality by using afterEach and checking the test results.
afterEach(() => {
const { currentTestName, testPath, testResults } = expect.getState();
const currentTestResult = testResults.find(test => test.fullName === currentTestName);
if (currentTestResult && currentTestResult.status === 'failed') {
console.log(`Test failed: ${currentTestName}`);
// Add your failure handling logic here
page.takeScrenshot();
}
});
test('example test', () => {
expect(true).toBe(false); // This will fail
});
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