简体   繁体   English

检查测试是否在 afterEach of Jest 中失败

[英]Check if test failed in afterEach of Jest

When one of my Jest tests fails I want to store a screenshot, but only when it fails.当我的一项Jest测试失败时,我想存储屏幕截图,但仅限于失败时。

Here is a piece of my test code as an example, the !passed part in the afterEach is not working.这是我的一段测试代码作为示例,afterEach 中的!passed部分不起作用。

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.但是我找不到 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...我尝试了一个 try/catch 围绕期望,但后来测试总是通过......

How can I check with Jest if my test failed in the afterEach?如果我的测试在 afterEach 中失败,我如何使用 Jest 进行检查?

Store current spec results in Jasmine and access it in afterEach .将当前规范结果存储在 Jasmine 中并在afterEach访问它。

@Niels van Reijmersdal is on the right track. @Niels van Reijmersdal 走在正确的轨道上。 However, the downside of taking a screenshot in specDone is that it runs after afterEach , so if there's something in afterEach that, say, navigates back a few screens, the screenshot you end up taking won't be representative of where the error took place.然而,考虑在截图下行specDone是,它运行afterEach ,所以如果有什么东西在afterEach说,认为导航回几个屏幕,屏幕截图,你最终以不能代表的地方采取了错误的地方. Here's an answer that allows you to take a screenshot immediately after the error occurs.这是一个答案,可让您在发生错误后立即截取屏幕截图。

  1. Add a custom Jasmine reporter for specStarted and store the spec results to jasmine.currentTest .specStarted添加自定义 Jasmine 报告specStarted并将规范结果存储到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.与此相关的不直观之处在于,即使我们在结果specStarted之前将其存储在specStarted中, jasmine.currentTest存储对result对象的引用,该引用将在规范运行时动态更新,因此当我们在afterEach访问它时,它将正确保存规范的结果。

  2. Check for failedExpectations in your afterEach and take a screenshot if there's been any failures.检查failedExpectations中的afterEach并在出现任何故障时截取屏幕截图。

     afterEach( async () => { if ( jasmine.currentTest.failedExpectations.length > 0 ) { // There has been a failure. await driver.takeScreenshot(); } } );

Seems the jasmine object can be used in Jest tests, but the currentSpec has been removed in the 2.x version. Jest 测试中似乎可以使用 jasmine 对象,但是 currentSpec 在 2.x 版本中已被删除。

I have found an alternative with the use of jasmine custom reports.我找到了使用 jasmine 自定义报告的替代方法。 Just make sure you also move the driver.quit() to the reporter as you might still need the driver after the test.只要确保你也将driver.quit()移动到报告器,因为你可能在测试后仍然需要驱动程序。

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

Here is an example how I solved it in my project: (Assuming that afterEach is used only for taking screenshots and not for cleanup and other navigates)这是我如何在我的项目中解决它的示例:(假设 afterEach 仅用于截屏而不用于清理和其他导航)

const testIt = (name, action) => {
    test(name, async () => {        
        try {         
            await action()} 
        catch (error) {           
            await screenshots.createScreenshot(page) //take screenshot 
            throw error
        }
    })
  }

describe('Test scenario 1', () => {
   
    testIt('test1 will Pass', async () => {
        expect(true).toBe(true)
    })
        
    testIt('test2 will Fail', async () => {
        expect(true).toBe(false)
    })

    afterEach(async () => {
        //ignored
    })

})

I use jest-html-reporters, and only failed tests will have attachment there (this solution did not require any other configurations).我使用 jest-html-reporters,只有失败的测试才会有附件(这个解决方案不需要任何其他配置)。 Result:结果:

  • test1 - passed, no screenshot test1 - 通过,没有截图
  • test2 - failed, has screenshot test2 - 失败,有截图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM