Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse code inside another spec.js?

Tags:

cypress

I have two test scripts that must be called by a third one. I don't would like to replicate the code for all test cases that uses the same two scripts and do many other things after.

I tried to use the require command but it seems to be ignored and the code after it is executed, skipping the intended script AbrirNavegador.spec.js

before(function() {require('./AbrirNavegador.spec.js')});

There's no information about error or something else. It's just skipped.

like image 991
Aloisio Farias Avatar asked May 18 '26 01:05

Aloisio Farias


1 Answers

I never got that to work. But I do use another work around. What I do:

// commands.js
Cypress.Commands.add('reuseMethod1', function({
  // first set of steps that need to be reused
})
Cypress.Commands.add('reuseMethod2', function({
  // second set of steps that need to be reused
})
// testscript_1.js
cy.reuseMethod1()
// testscript_2.js
cy.reuseMethod1()
cy.reuseMethod2()

You can call the methods at any place, so also in a before/beforeEach/after/afterEach. So the only code duplication you have is the part of calling the method.

like image 108
Mr. J. Avatar answered May 22 '26 13:05

Mr. J.