我使用 Cypress 的 before() 函数来组织我的测试。但不幸的是,这运行不稳定。我的意思是,测试第一次失败,然后在随后的几次中成功。这是因为 before 在描述()的测试中运行了不止一次。
这是我期望的工作方式,当我按“再次运行所有测试”时,它始终有效。我可以得出结论,这种片状现象仅在我第一次运行测试套件时(未设置会话时)出现:
我的测试代码是这样的:
describe('portaal', () => {
before(() => {
})
it('test1', () => {
});
it('test2, () => {
});
});
describe('portaal', () => {
before(() => {
})
it('test3', () => {
})
it('test4', () => {
});
});
我有一个名为 e2e.ts 的 e2e 配置文件,其中包含以下内容:
before(() => {
const Api = Cypress.env().Api;
cy.ntlm(Api.hostUrl, Api.username, Api.password, Api.domain);
});
有没有办法在工作前让它像第一次运行时那样?
这是一个可能的答案,尽管我更喜欢看到更多细节。
cy.session()
命令用于缓存登录详细信息。它应该始终用于beforeEach()
而不是before()
。
这是因为第一次调用
cy.session
会进行真正的(实时)登录(在 test1
之前调用时),但是在 test2
之前调用时,它实际上并没有进行登录,它只是返回在第一次打电话。
这里是文档参考会话示例。
会话命令的格式为
cy.session(id, setup, options)
,options
可以带validate
函数,当您进行不稳定测试时推荐使用。
这是您的代码应该使用的模式。我把代码展开来注释,但通常你可以把它压缩下来。
beforeEach(() => {
cy.session(
'login', // session id
() => { // setup function, called only once
const Api = Cypress.env().Api;
cy.ntlm(Api.hostUrl, Api.username, Api.password, Api.domain);
},
{
validate: () => { // validate function, use to retry login when tests are flaky
cy.contains('a', 'View') // add check on the element that fails when flaky
}
}
})
// Always visit right after cy.session
cy.visit(...)
})
由于错误消息中提到了“查看”按钮,因此最好检查
cy.session()
验证功能,因为当登录失败时,该按钮不会出现在页面上。
当验证函数失败时,
cy.session()
知道它不能信任缓存的凭据,并且它将重新运行设置函数。
这是“再次运行所有测试”的自动版本(期望它只是再次运行登录)。这将确保代码保留在
beforeEach()
中并重复登录,直到成功登录。