Check if test failed in afterEach of Jest

大憨熊 提交于 2020-01-14 10:07:48

问题


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?


回答1:


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');
  });
});


来源:https://stackoverflow.com/questions/42000137/check-if-test-failed-in-aftereach-of-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!