【问题标题】:Cypress access alias with this.* doesn't works带有 this.* 的赛普拉斯访问别名不起作用
【发布时间】:2021-04-05 23:21:58
【问题描述】:

我在理解赛普拉斯文档时遇到了一点问题。在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);
});

但是当我尝试重现它时,我不断收到错误消息: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");
                
            });
        });
    });
});

还有我的任务

/**
 * @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.* 模式。

【问题讨论】:

  • 我知道this one的存在,可惜他们屈服于cy.get()的使用

标签: testing automated-tests this cypress arrow-functions


【解决方案1】:

在修改了代码后,我意识到我在步骤定义中使用了arrow function

it("Test with task", () =&gt; { ... }

我这样做只是因为我在VSC中使用了大量的sn-ps代码,并没有注意使用的语法。

所以,看到它之后,我记得它永远不会起作用,正如MDN documentation 所说:

箭头函数表达式是传统表达式的紧凑替代 函数表达式,但有限,不能全部使用 情况。

差异与限制:

  • 没有自己的绑定到 this super,不应用作 methods
  • 没有argumentsnew.target 关键字。
  • 不适用于callapplybind方法,这些方法一般依赖于建立scope
  • 不能用作constructors
  • 不能在其正文中使用yield

解决方案很简单,用函数定义替换它:

it("Test with task", function () { ... }

this 上下文符合预期

历史的道德,不要盲目相信你的代码编辑器(即使它的 VSC)

【讨论】:

  • 这对我来说更糟,因为他们在柏树网站上documented it...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-18
  • 2020-08-15
  • 1970-01-01
  • 1970-01-01
  • 2020-10-28
  • 1970-01-01
  • 2020-12-23
相关资源
最近更新 更多