我需要根据Cypress.io中的夹具返回的对象数量来运行测试'n‘次。我正在使用forEach方法暴露由柏树进行循环。我在“it”命令的外部空间使用forEach循环,但在内部描述。我得到了一个未定义的错误的夹具对象。见下面的代码:
describe("Search by people returns expected result", () => {
before(() => {
cy.fixture('people').then(function(peopleJson) {
this.peopleJson = peopleJson;
});
cy.fixture('planets').then(function(planetsJson) {
this.planetsJson = planetsJson;
});
})
beforeEach(() => {
cy.visit('/')
});
this.peopleJson.forEach(data => {
it('Verify people by'+ data.name, function() {
cy.searchBy('people', data.name)
cy.verifyPerson(data)
})
})
afterEach(() => {
cy.log("inside aftereach!")
clearForm();
})});我在Cypress编译器中获得的
错误消息是
以下错误起源于您的测试代码,而不是来自Cypress。
无法读取未定义的属性(读取'peopleJson')当Cypress检测到来自您的测试代码的未明错误时,它将自动失败当前的测试。
Cypress无法将此错误与任何特定测试相关联。
我们动态地生成了一个新的测试来显示这个失败。
this.peopleJson现在还没有定义,但是如果我在' if‘块中使用forEach循环,那么代码就可以工作了。但是我希望动态地生成测试用例,并且如果任何测试用例对于任何数据对象都失败了,那么其他的测试就会继续进行。
我尝试了另一种方法,将治具命令放在forEach的上方,但这也不起作用。我参考了Cypress.io的原始文档,我发现一个固定的调用必须是它块的一部分,所以我不能在forEach循环的上方使用夹具。
处理这种情况的最佳方法是什么?
People.json
[
{
"name": "R2-D2",
"gender": " n/a ",
"birthYear": " 33BBY ",
"eyeColor": " red ",
"skinColor": " white, blue ",
"description": "name with numbers"
},
{
"name": "Obi-Wan Kenobi",
"gender": " male ",
"birthYear": " 57BBY ",
"eyeColor": " blue-gray ",
"skinColor": " fair ",
"description": "name with dash and space"
},
{
"name": "Boba Fett",
"gender": " male ",
"birthYear": " 31.5BBY ",
"eyeColor": " brown ",
"skinColor": " fair ",
"description": "name consists of two words"
},
{
"name": "Dormé",
"gender": " female ",
"birthYear": " unknown ",
"eyeColor": " brown ",
"skinColor": " light ",
"description": "name with special character"
},
{
"name": "Ki-Adi-Mundi",
"gender": " male ",
"birthYear": " 92BBY ",
"eyeColor": " yellow ",
"skinColor": " pale ",
"description": "name with two dashes"
}
]发布于 2022-01-17 15:00:25
因为您希望在it块之外使用json文件,所以不能使用beforeEach()。相反,您必须在测试中导入json文件并应用forEach。
import peopleJson from '../fixtures/people.json' //Assuming your test is inside integration folder
describe('Search by people returns expected result', () => {
beforeEach(() => {
cy.visit('/')
})
peopleJson.forEach((data) => {
it('Verify people by' + data.name, function () {
cy.searchBy('people', data.name)
cy.verifyPerson(data)
})
})
afterEach(() => {
cy.log('inside aftereach!')
clearForm()
})
})发布于 2022-01-18 19:21:29
要使用this关键字,您必须使用常规函数function () {},而不是fat箭头() => {}
describe("Search by people returns expected result", () => {
before( function () { // changed to regular function
cy.fixture('people').then(function(peopleJson) {
this.peopleJson = peopleJson;
});
cy.fixture('planets').then(function(planetsJson) {
this.planetsJson = planetsJson;
});
})
beforeEach(() => {
cy.visit('/')
});
this.peopleJson.forEach(data => {
it('Verify people by'+ data.name, function() {
cy.searchBy('people', data.name)
cy.verifyPerson(data)
})
})
afterEach(() => {
cy.log("inside aftereach!")
clearForm();
})});https://stackoverflow.com/questions/70741740
复制相似问题