Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest onFailure hook

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?

like image 589
Pavel S. Avatar asked Sep 14 '25 03:09

Pavel S.


1 Answers

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
});
like image 58
Subrahmanyam Avatar answered Sep 15 '25 15:09

Subrahmanyam