【问题标题】:Method to not catch element in cypress test everytime its needed每次需要时都不在柏树测试中捕获元素的方法
【发布时间】:2022-10-15 03:35:45
【问题描述】:

我正在为 cypress 中的 Dark Mode Actions 编写测试,并且我主要在 header 上操作。因为它,我经常使用 cy.get("header) 来捕捉它。我想知道是否有任何方法可以将它保存在任何变量中,所以不需要每次都捕捉它并使用 header.contains 之类的东西示例。赛普拉斯的文档说简单的 const header = cy.get("header") 不起作用。你知道解决这个问题的任何方法,所以我的代码会更干净一点吗?

部分测试代码

  it("toggles darkmode", () => {
    //when
    cy.visit("localhost:3000");
    cy.get("header").contains("title", "moon-icon").click({ force: true });
    cy.get("header").should("contain", "sun-icon");
    cy.get("header").contains("title", "sun-icon").click({ force: true });
    cy.get("header").should("contain", "moon-icon");
  });
  it("remebers dark mode after refresh", () => {
    //when
    cy.visit("localhost:3000");
    cy.get("header").contains("title", "moon-icon").click({ force: true });
    cy.reload();
    //then
    cy.get("header").should("contain", "sun-icon");
  });

【问题讨论】:

    标签: javascript cypress


    【解决方案1】:

    假设您在同一个 describe 块中的所有测试都具有相同的设置,您可以在 beforeEach 中为 cy.get('header') 起别名。

    describe('test', () => {
      beforeEach(() => {
        cy.visit('localhost:3000');
        cy.get('header').as('header');
      });
    
      it("toggles darkmode", () => {
        //when
        cy.get("@header").contains("title", "moon-icon").click({ force: true });
        cy.get("@header").should("contain", "sun-icon");
        cy.get("@header").contains("title", "sun-icon").click({ force: true });
        cy.get("@header").should("contain", "moon-icon");
      });
    });
    

    【讨论】:

    • 但它会改变什么?我只需要 cy.get("@header) 而不是 cy.get("header),对吗?
    【解决方案2】:

    查看.within() 以设置命令范围。

    cy.get("header").within($header => {
      cy.contains("title", "moon-icon")
        .click()
        .should("contain", "sun-icon")
    
      cy.contains("title", "sun-icon")
        .click()
        .should("contain", "moon-icon")
    })
    

    【讨论】:

      猜你喜欢
      • 2021-01-27
      • 2018-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多