Ad

Converting Cypress File Into A More Appropriate Format For Exporting

I am struggling to put best practises into action, converting an existing file for Cypress testing into a more appropriate format for exporting and importing.

Currently:

support-file.js

export const1 = () => cy.get('#someId1');
export const2 = () => cy.get('#someId2');
export const3 = () => cy.get('#someId3');

export function myFunct1() {
    // Do something
}

export function myFunct2() {
    // Do something
}

export function myFunct3() {
    // Do something
}

file-where-used.js

import {
  const1, const2, const3,
  myFunct1, myFunct2, myFunct3
}

// usage of the consts/functs below

I have experimented with trying to get them into a format such that I do not have to import each separately, but I cannot figure it out... I thought, perhaps wrapping all as a class and exporting that, which does work but only when using a require rather than import... And I also found difficulty in exporting my const variables...

attempt

export const1 = () => cy.get('#someId1');
export const2 = () => cy.get('#someId2');
export const3 = () => cy.get('#someId3');

class myClass {
    myFunct1() {
        // Do something
    }

    myFunct2() {
        // Do something
    }

    myFunct3() {
        // Do something
    }
}
module.exports = new myClass();
Ad

Answer

You can cut your issues up in several steps.

Custom Commands/functions

Firstly you are creating custom commands like this one:

export function() {
    // Do something
}

By putting that function in the file cypress/support/commands.js you don't have to import it in the integration files, but you do have to rewrite is like this:

Cypress.Commands.add('myFunct1', function () {
    // Do something
})

What you end up in the integration file is this:

cy.myFunct1()

Global variables

You are assigning global variables like this:

export const1 = () => cy.get('#someId1');
export const2 = () => cy.get('#someId2');
export const3 = () => cy.get('#someId3');

Start with rewriting them to be a constant:

const const1 = () => cy.get('#someId1');
const const2 = () => cy.get('#someId2');
const const3 = () => cy.get('#someId3');

You'll always need to import them one by one, but you can combine them as long as they are in one file. You could do so by importing them into the testfile like this:

import {const1, const2, const3} from '<FILE_DIRECTORY>'

Now they are available trough the whole testfile.

Ad
source: stackoverflow.com
Ad