[英]Cypress - how to send parameters to same function inside it's callback
我正在尝试在我的 cypress 项目中实施装置以避免重复发送相同的请求。
命令“ReadFixture”从夹具文件返回数据:
Cypress.Commands.add("ReadFixture", (fixtureName, firstKey, secondKey = "") => {
let fixturePath = `cypress/fixtures/${fixtureName}.json`;
if (secondKey.length === 0) {
cy.readFile(fixturePath).then(fixture => {
let dataArray = [];
let fixtureKeys = Object.keys(fixture);
fixtureKeys.forEach(key => {
let data = fixture[key][firstKey];
dataArray.push(data);
});
return cy.wrap(dataArray);
});
}
else {
cy.readFile(fixturePath).then(fixture => {
let dataArray = fixture[secondKey][firstKey];
});
return cy.wrap(dataArray);
};
});
数据采用json结构:
{
"id_0": {
"id": "id_0",
"more_data": [
"string_0"
]
},
"id_1": {
"id": "id_1",
"more_data": [
"string_1",
"string_2"
]
}
}
对于某些测试,只需要“id”,例如测试示例:
it("Level 1", () => {
cy.ReadFixture("fixture_name", "id").then(urlKeys => {
urlKeys.forEach(keyUrl => {
cy.request({
method: "GET",
url: `${reqUrl}/${keyUrl}`
}).then(response => {
expect(response.status).to.be.equal(200);
});
});
});
})
一切都按预期工作,但是,对于其他测试,需要单个“id”的“more_data”。 我的方法是读取夹具两次 - 首先获取“id”数组,就像在“Level 1”测试中一样,然后为数组中的每个“id”获取“more_data”。 例子:
it("Level 2", () => {
cy.ReadFixture("fixture_name", "id").then(urlKeys => {
urlKeys.forEach(keyUrl => {
cy.ReadFixture("fixture_name", "more_data", keyUrl).then(keyData => {
cy.request({
method: "GET",
url: `${reqUrl}/${keyUrl}/more_data`
}).then(response => {
expect(response.status).to.be.equal(200);
expect(response.body.more_data).to.be.eql(keyData);
});
});
});
});
});
问题是,当
cy.ReadFixture("fixture_name", "more_data", keyUrl)
被调用,keyUrl 没有为它定义,并且由于 if 语句,命令从所有“id”返回“more_data”数组。 此外,keyUrl 不能传递给请求。 是否有可能解决这个问题,或者我使用的方法完全错误?
尝试更改您的 else 块以wrap
值wrap
在您的then
回调中:
else {
cy.readFile(fixturePath).then(fixture => {
let dataArray = fixture[secondKey][firstKey];
return cy.wrap(dataArray);
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.