Cypress reuse test cases in multiple test suites

11.4k Views Asked by At

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.

2

There are 2 best solutions below

0
Alapan Das On BEST ANSWER

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')
1
Seth On

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();
    ...
  });
});