简体   繁体   中英

Cypress reuse test cases in multiple test suites

I am new to Cypress and trying out one POC.

The application I am working on requires me to test the same component in different test suites. Is there any why in which I can avoid rewriting the same chunk of code, like using function?

export function testWelcomeBanner() {
    ...
 welcomeBanner.should('have.text', 'welcome');
    ...
}

I did try some ways, like trying to call this function from it block in test suites etc. but received errors. Any help appreciated.

You can use custom commands to reuse your scripts. You can read more about custom commands from the cypress docs .

You can write your reusable functions under cypress/support/command.js

Cypress.Commands.add('welcomeBanner', (text) => {
  cy.get('locator').should('have.text', 'text');
})

You can use the above command in any of your tests like

cy.welcomeBanner('Welcome Text')

Cypress recommends using functions just as you would with plain old JavaScript.

...writing Cypress tests is JavaScript, and it's often more efficient to write a function for repeatable behavior.

Source

Put reusable functions into a separate file.

utils.js :

/// <reference types="cypress" />

export function testWelcomeBanner() {
  // Add more logic as needed here. You can also return
  // the result of your `cy.` call.
  cy.get("div.welcomeBanner")
    .should("have.text", "welcome");
}

Then import those functions in your Cypress tests.

myTest.spec.js :

/// <reference types="cypress" />
import { testWelcomeBanner } from "../utils.js"; // Adjust the path for your environment

describe("testing", () => {
  it("can do something", () => {
    ...
    testWelcomeBanner();
    ...
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM