我有一个简单的 Cypress 测试:
describe('My First Test', () => {
it('Go to login page', () => {
cy.visit('http://localhost:3000')
cy.contains('Log in').click()
})
it('Login with local account', () => {
cy.get('input[type=email]').type('123@123.com')
cy.get('input[type=password]').type('asd123')
cy.contains('Log in').type('{enter}')
})
})
第一个断言检查是否存在带有文本 Log in
的元素,然后单击它。第二个断言尝试登录。
我已将 Log in
按钮中的文本更改为 Assertion Failed
。所以现在第一个断言失败了,但它仍然运行第二个断言,即使我没有被重定向到登录页面。
当断言失败时,有没有办法取消正在运行的规范?
答案 0 :(得分:4)
你也可以使用
afterEach(() => {
if (cy.state('test').state === 'failed') {
Cypress.runner.stop()
}
})
但这有一个问题,您的 after()
钩子都不会运行,包括代码覆盖率之类的插件。
更好的解决方案是动态跳过以下测试,类似于此答案How to add test case grouping in Cypress
beforeEach(function() {
const suite = cy.state('test').parent
if (suite.tests.some(test => test.state === 'failed')) {
this.skip()
}
})
这是我的简化测试
describe('all tests', () => {
describe('fail fast', () => {
beforeEach(function() { // move up to apply to all tests
const suite = cy.state('test').parent;
if (suite.tests.some(test => test.state === 'failed')) {
console.log(`skipping test "${cy.state('test').title}"`)
this.skip()
}
})
after(() => {
console.log('after') // runs
})
it('fails', () => {
expect(true).to.eq(false) // fails
})
it('next', () => {
expect(true).to.eq(true) // skipped
})
})
describe('no fail fast', () => {
it('no skip', () => {
expect(true).to.eq(true) // runs
})
})
})
答案 1 :(得分:-1)
您可以添加一个 afterEach()
并这样写:
afterEach(function() {
if (this.currentTest.state === 'failed') {
Cypress.runner.stop()
}
});
或
您可以使用插件 cypress-fail-fast 并在测试级别对其进行配置:
describe("All tests", {
failFast: {
enabled: false, // Children tests and describes will inherit this configuration
},
}, () => {
it("sanity test", {
failFast: {
enabled: true, // Overwrite configuration defined in parents
},
}, () => {
// Will skip the rest of tests if this one fails
expect(true).to.be.true;
});
it("second test",() => {
// Will continue executing tests if this one fails
expect(true).to.be.true;
});
});
或者,通过在 cypress.json
中写入,全局适用于所有规范:
{
"env":
{
"FAIL_FAST_ENABLED": true
}
}