Search code examples
cypresscucumberjs

How to implement a custom command In Cypress test


I wrote a custom command to get authentication token from the window like below

Cypress.Commands.add("getToken", AUTH => {
 return cy.window().then(window => window.localStorage.getItem(AUTH));
});
const authToken = JSON.parse(window.localStorage.getItem("AUTH")); 

authToken = returned the authtoken. I want to know how to make`enter code here` this as 
function/custom command so that the other t`enter code here`est could use this.

Solution

  • I suggest something like this:

    describe('', () => {
      let tokens = {};
    
      it('', () => {
        cy
          .getToken('AUTH', ({ token }) => {
            Object.assign(tokens, { auth: token });
          })
          .request({
            headers: { "Content-Type": "application/json", Authorization: `Bearer ${tokens.auth}`, }
          })
    
      });
    });
    

    Also you have to change little bit getToken command:

    Cypress.Commands.add("getToken", (AUTH, cb) => {
     return cy.window().then(window => cb(window.localStorage.getItem(AUTH)));
    });