我在理解 Cypress 文档时遇到了一些问题。在 alias section他们添加了一个使用 this.*
引用访问带有固定装置的别名的用例:
beforeEach(() => {
// alias the users fixtures
cy.fixture("users.json").as("users");
});
it("utilize users in some way", function () {
// access the users property
const user = this.users[0];
// make sure the header contains the first
// user's name
cy.get("header").should("contain", user.name);
});
但是当我尝试重现它时,我不断收到错误:无法读取未定义的属性“SOAP_body”
。
我不明白我的错误在哪里。这是我的规范:
/// <reference types="cypress"/>
describe("SOAP API Test", () => {
beforeEach(() => {
cy.fixture("SOAP_body.xml").as("SOAP_body");
});
it("Test with task", function () {
const body = this.SOAP_body;
cy.request({
method: "POST",
headers: {
"content-type": "text/xml; charset=utf-8",
Authorization: "Token myVerySecretToken",
SOAPAction: "http://tempuri.org/TrackingFull",
},
url: `https://path.of/the/application.asmx`,
body: body,
failOnStatusCode: false,
}).then((result) => {
expect(result.status).to.equal(200);
cy.task("XMLtoJSON", result.body).then((response) => {
expect(
response.elements[0].elements[1].elements[0].elements[0]
.elements[1].elements[0].elements[0].elements[0]
.elements[0].elements[0].text
).to.equal("something");
});
});
});
});
和我的任务
/**
* @type {Cypress.PluginConfig}
*/
module.exports = (on, config) => {
on("task", {
XMLtoJSON(XML_body) {
var convert = require("xml-js");
let result = convert.xml2js(XML_body, {
compact: false,
spaces: 2,
});
return result;
},
});
};
在 const 定义之前使用 debugger
我可以看到变量未定义
我确实了解 cy.get()
,但我只是想了解如何使用 this.*
模式。
最佳答案
摆弄代码后,我意识到我在步骤定义中使用了箭头函数
:
it("使用任务进行测试", () => { ... }
我这样做只是因为我在VSC中使用了很多代码片段,而从未关注过所使用的语法。
所以,看到它之后,我记得它永远不会起作用,因为 MDN documentation说:
An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations.
Differences & Limitations:
解决方案很简单,只需将其替换为函数定义即可:
it("使用任务进行测试", function () { ... }
并且 this
上下文符合预期
历史的教训,不要盲目相信你的代码编辑器(即使是 VSC)
关于testing - 使用 this.* 的 Cypress 访问别名不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66960919/