Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run function when any test fails - Jest

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.

like image 495
Tyler Clark Avatar asked Jan 22 '18 18:01

Tyler Clark


2 Answers

@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
  });
});
like image 51
Jeremy Avatar answered Oct 17 '22 03:10

Jeremy


Store current spec results in Jasmine and access it in afterEach.

  1. 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.

  2. 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.
      }
    } );
    
like image 41
Joshua Pinter Avatar answered Oct 17 '22 02:10

Joshua Pinter