Reputation: 203
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.
Upvotes: 10
Views: 12500
Reputation: 6842
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.
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();
...
});
});
Upvotes: 15
Reputation: 18618
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')
Upvotes: 17