Aloisio Farias
Aloisio Farias

Reputation: 33

How to reuse code inside another spec.js?

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.

Upvotes: 3

Views: 499

Answers (1)

Mr. J.
Mr. J.

Reputation: 3721

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.

Upvotes: 2

Related Questions