As *_*ves 2 testing automated-tests this arrow-functions cypress
我在理解 Cypress 文档时遇到了一些问题。在别名部分,他们添加了一个使用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);
});
Run Code Online (Sandbox Code Playgroud)
但是当我尝试重现它时,我不断收到错误:Cannot read property 'SOAP_body' of undefined
。
我不明白我的错误在哪里。这是我的规格:
/// <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");
});
});
});
});
Run Code Online (Sandbox Code Playgroud)
和我的任务
/**
* @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;
},
});
};
Run Code Online (Sandbox Code Playgroud)
在 const 定义之前使用debugger
我可以看到变量未定义
我确实知道cy.get()
,但我只是想学习如何使用该this.*
模式。
在摆弄代码后,我意识到我arrow function
在步骤定义中使用了:
it("Test with task", () => { ... }
我这样做只是因为我在VSC中使用了很多代码片段,并且从未关注过所使用的语法。
所以,在看到它之后,我记得它永远不会起作用,正如MDN 文档所说:
箭头函数表达式是传统函数表达式的紧凑替代方案,但有局限性并且不能在所有情况下使用。
差异和限制:
解决方案很简单,只需将其替换为函数定义即可:
it("Test with task", function () { ... }
上下文this
正如预期的那样
历史告诉我们,不要盲目相信你的代码编辑器(即使它是 VSC)
归档时间: |
|
查看次数: |
2401 次 |
最近记录: |