[英]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.