使用 Cypress.Commands.overwriteQuery 出现错误

Dhi*_*man 4 javascript cypress cypress-custom-commands

我在覆盖该方法时收到此错误contains()

无法读取 cypress 中未定义的属性(读取“hasPreviouslyLinkedCommand”)

这是commands.js文件:

Cypress.Commands.add("clickOnLinks", (linkText) => {
  cy.get("a").contains(linkText).click();
});

// overwriting contains()
// passing the same parameter for the contains method

Cypress.Commands.overwriteQuery(
  "contains",
  (originalFn, subject, filter, text, options = {}) => {
    // determine if the filter argument was passed

    if (typeof text === "object") {
      options = text;
      text = filter;
      filter = undefined;
    }
    options.matchCase = false;

    return originalFn(subject, filter, text, options);
  }
);
Run Code Online (Sandbox Code Playgroud)

这是我的测试文件:

describe("Custom command", () => {
  it("overwriting the custom commands", () => {
    cy.visit("https://magento.softwaretestingboard.com/");

    // calling clickOnLinks command to click on the links
    cy.clickOnLinks("RADIANT TEE").should("exist");
    // verifying after performing click action

    cy.get("span[class='base']").should("have.text", "Radiant Tee");
  });
});
Run Code Online (Sandbox Code Playgroud)

我正在使用最新版本的 cypress - 12.7.0

我也尝试过使用这个,但没有运气 - Cypress.Commands.overwriteQuery

我缺少什么?有人可以帮忙吗?

Fod*_*ody 5

主要问题是this绑定originalFn没有设置,可以用 修复originalFn.bind(this)

我从源中获取了参数命名和解析,并将选项(又名 userOptions)默认为 ,{}以防它们未通过。

有一件奇怪的事情 -prevSubject不再存在。当从命令更改为查询时,可能会发生这种情况contains,但尚未弄清楚它是如何获取 prevSubject 的。

无论如何,这都过去了cy.get('a').contains('RADIANT TEE')

我还没有测试其他变体。

Cypress.Commands.overwriteQuery(
  "contains",
  function (contains, filter, text, userOptions = {}) {

    // This is parameter resolution from Cypress v12.7.0 source
    if (Cypress._.isRegExp(text)) {
      // .contains(filter, text)
      // Do nothing
    } else if (Cypress._.isObject(text)) {
      // .contains(text, userOptions)
      userOptions = text
      text = filter
      filter = ''
    } else if (Cypress._.isUndefined(text)) {
      // .contains(text)
      text = filter
      filter = ''
    }

    userOptions.matchCase = false;

    let contains0 = contains.bind(this)    // this line fixes the error

    return contains0(filter, text, userOptions)
  }
)
Run Code Online (Sandbox Code Playgroud)