I want to run a function
/ task
whenever any jest
test fails. Instead of wrapping all of my test's with try
/ catch
or add an if
check, is there a way I can utilize the afterEach
?
If the test fails then I want it to fail, just run a separate function.
For example:
test('nav loads correctly', async () => {
const listItems = await page.$$('[data-testid="navBarLi"]')
expect(listItems.length).toBe(4)
if (listItems.length !== 4)
await page.screenshot({path: 'screenshot.png'})
})
This is adding an if check... But I want something more robust for all of my tests.
@Tyler Clark I haven't attempted this with afterEach
, but I suspect you could apply something similar this my SO answer here. (pasting a version of it below for context - altered to work with afterEach
)
const GLOBAL_STATE = Symbol.for('$$jest-matchers-object');
describe('Describe test', () => {
afterEach(() => {
if (global[GLOBAL_STATE].state.snapshotState.matched !== 1) {
console.log(`\x1b[31mWARNING!!! Catch snapshot failure here and print some message about it...`);
}
});
it('should test something', () => {
expect({}).toMatchSnapshot(); // replace {} with whatever you're trying to test
});
});
afterEach
.Add a custom Jasmine reporter for specStarted
and store the spec results to jasmine.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 the result
object which will get updated dynamically as the spec runs so when we access it in our afterEach
, it will be holding the results of the spec properly.
Check for failedExpectations
in your afterEach
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(); // Or whatever else you want to do when a failure occurs.
}
} );
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