How to skip support/index.js for certain spec files in Cypress

Viewed 1430

Is it possible to skip the beforeEach function in my Cypress index.js support file, for a certain spec file (access.spec.js)?

index.js

// This example support/index.js is processed and
// loaded automatically before your test files.

beforeEach(function () {
  cy.request('POST', 'https://exampleURL.com', {
    email: 'email',
    password: 'password'
  }).then((response) => {
    cy.setCookie('accessToken', response.body.AccessToken);
  });

  cy.setCookie('email', 'email');
  cy.setCookie('environment', '3');
  cy.setCookie('name', 'name');
}

access.spec.js

it("it should send user back to login screen when AccessToken is missing", () => {
  // Code here
});
1 Answers

From a conventional perspective, a beforeEach block in support/index.js should only have code that applies to all test specs. If logic only pertains to some tests and not to others, it should not be placed in support/index.js.

Trying to override how Cypress intends to use support/index.js is working against the framework, and not with it.

Subsequently, an alternative to duplicating this beforeEach logic in all tests that require it, would be to create a Custom Command, like this:

Cypress.Commands.add('login', () => {
  cy.request('POST', 'https://exampleURL.com', {
    email: 'email',
    password: 'password'
  }).then((response) => {
    cy.setCookie('accessToken', response.body.AccessToken);
  });

  cy.setCookie('email', 'email');
  cy.setCookie('environment', '3');
  cy.setCookie('name', 'name');
})

...and then, from within the specs that require this functionality, you could have a simpler beforeEach block, like this:

beforeEach(function() {
  cy.login();
});

However, given that your access.spec.js test is concerned with a missing accessToken, you would not use the beforeEach block in that particular test. Instead, copy the login code into that test, and use cy.route instead of cy.request (which hits your actual endpoint), so that you can stub out a response that does not return an accessToken.

Related