Cypress - 检查全局 afterEach 中的测试失败

问题描述 投票:0回答:3

如果测试(

afterEach
)失败,是否可以检查全局
it

这样的全局

afterEach
位于
support/index.js

afterEach(() => {
  // check if test failed and perform some actions
})
testing automated-tests cypress
3个回答
3
投票

您可以使用

afterEach
钩子并保留在 Cypress 上下文的范围内(其中
cy
命令可用),例如:

afterEach(function() {
    if (this.currentTest.state === 'failed') {
        // your code
    }
});

参考:https://github.com/cypress-io/cypress/discussions/15047

或者您可以使用

test:after:run
事件并切换到
node
上下文(可以在 Cypress 范围之外执行任何类型的节点代码,例如访问数据库或文件系统),例如:

Cypress.on('test:after:run', (test, runnable) => {
    if (test.state === 'failed') {
        // your code
    }
});

参考:https://docs.cypress.io/api/events/catalog-of-events#Cypress-Events


0
投票

您寻求的是 after:spec 并通过插件公开。您将可以访问规格和结果。 https://docs.cypress.io/api/plugins/after-spec-api#Syntax


0
投票

接受的答案对我不起作用,但是我找到了这个解决方案:

  afterEach(() => {
    if(Cypress.state().test.state !== 'passed') {
      cy.task('log', "Test did not pass: " + Cypress.state().test.title);
    }
  });

上述解决方案的优点是您可以使用

cy.task(..)
,与:

不同
Cypress.on('test:after:run', (test, runnable) => {
    if (test.state === 'failed') {
        // your code
    }
});

哪个不能用

task

© www.soinside.com 2019 - 2024. All rights reserved.