Search
⌘K
    to navigateEnterto select Escto close

    Utility Functions in Cypress

    • Sometimes, the piece of code is redundant and we don't we don't require it in all the test cases. We can create utility functions and move such code there.
    • Like custom commands, it's also easy to work with utility functions.
    • We can create a separate folder as utils in support folder and store our functions in a file in that folder.

    Consider the following example of utility function for login.

    1//cypress/support/utils/common.js
    2
    3export const loginViaUI = (username, password) => {
    4  cy.get("[data-cy='login-email-field']").type(username);
    5  cy.get("[data-cy='login-password-field']").type(password);
    6  cy.get("[data-cy='submit-button']").submit()
    7}

    This is how we can use utility function in our test case:

    1import {
    2  loginViaUI
    3} from '../support/utils/common.js';
    4
    5describe("Login", () => {
    6  it('should allow user to log in', () => {
    7    cy.visit('/login');
    8    loginViaUI('username', 'password');
    9  });
    10});

    Commands vs Utility Functions

    Doesn't it seem that both utility function or a command does the similar thing? Maybe yes. But which one to prefer utility function or a command ?

    The thumb rule: If the code being used in almost every test suite, we can create a custom command for it. The benefit of this is that we don't have to import the js file to use the command, it is available directly on cy object i.e. cy.loginViaUI().

    But, this doesn't mean that we should use commands for everything. If the code is used in only some of the test suite, we can create a utility function and import it whenever needed.

    Previous
    Next