0

after hook doesnt work for the first time in cypress but when i retry, it works. in the after hook i call a cy.request and i get a token from another request . i run the token request in before all the tests to make sure i got the token here is the code in the main tests

describe('test', () => {


  before(() => {
   
    Login.userLg();
  });

  it('first test', () => {
    cy.visit('`url`);

    // some code to test 
  });

  // delete user
  afterEach(() => {
   user.delete();
  });
});

here is the code of the user function in another file (tokenFile)

delete() {
    failOnStatusCode: false
    cy.request({
      method: 'PATCH',
      url: `url`,
      headers: {
        Authorization: 'Bearer ' + Cypress.env('token'),
        
      },
      body: {
        name: user,
        
      },
    });
  }

here is the code to get the token in a third file

describe('token', () => {
  it('get operator token', () => {
    cy.request({
      method: 'POST',
      url: 'url',
      form: true,
      body: {
      
        grant_type: 'password',
        username: 'user',
        password: 'pass',
      },
    }).then((response) => {
      Cypress.env('token', response.body.token);
    });
  });
});

i call the token request in support/e2e.ts

import './tokenFile';

i tried to put the fucntion in after hook ,put in before hook before login , also i tried afterEach and it didn'T work , i tried to put the token request in command file . nothing works

soso
  • 1
  • What isn't working? The code isn't running? Your request isn't successful? What is the error you receive? – agoff Nov 21 '22 at 16:12

1 Answers1

0

You should really clear state before tests run rather than after. This is in the official Cypress docs:

https://docs.cypress.io/guides/references/best-practices#Using-after-or-afterEach-hooks

One other benefit of doing this is that if you have a test failure you preserve all the data that the test failed with meaning you can debug the issue.

Simon D
  • 131
  • 1
  • 7
  • But it doesn't really answer the question - he already tried it in the before() hook. – Aureuo Nov 29 '22 at 19:59
  • He says ***doesn't work for the first time in cypress but when I retry, it works*** - that's the question, not if the before or after hook should be the one to use. – Aureuo Dec 06 '22 at 22:31