How to write reusable "before" in Cypress?

211 Views Asked by At

I would like to write reusable "before" section, but has failed to pass variable from main file (A.js) to imported code (HelloUtil.js). Thanks in advance for any suggestions given.

A.js

import * as UTIL from "./HelloUtil"

let variableFileA = "Hello"

// I hope the imported 'before' section is able to get 'variableFileA'

describe(`Do something`, () => {
    it('A "It" section', () => {
        cy.log("....")
    });
})

HelloUtil.js

before('Reusable "before" 1', () => {
    cy.log("lets begin....")
});

before('Reusable "before" 2', () => {
    cy.log("print variable:"+variableFileA)
});

The result that I received:

enter image description here

2

There are 2 best solutions below

0
On BEST ANSWER

No, this is not what's going to work.

You'd need to define variableFileA variable in HelloUtil.js if you want to use the variable in there. Or you can pass the variable as an argument. But you are not doing either.

What can work is this:

utils.js

export const beforeFunc = () => {
  cy
    .log('Before func from utils.js');
};

test.js

import { beforeFunc } from './utils';

describe('My example test suite', () => {

  before(beforeFunc);
});

If you want to pass some argument, you can do it like so:

utils.js

export const beforeFunc = (greetings) => {
  cy
    .log(greetings);
};

test.js

import { beforeFunc } from './utils';

describe('My example test suite', () => {

  before(() => beforeFunc('Hi'));
});

And the result from the test runner:

enter image description here

0
On

I would use a custom command that can be pasted in any section - be it in before, after, it etc. For example:

import file from 'filePath'
Cypress.Commands.add('reusableBefore2', () => {
   cy.log("print variable:" + file)
})

And you can call it any time with: cy.reusableBefore2()