Warm tip: This article is reproduced from stackoverflow.com, please click
cypress promise

Cypress: Returning value in promise within custom command?

发布于 2020-04-13 09:42:22

So I am trying to use a custom command to reduce the need to write the same thing in multiple files. Specifically this is for logging in and setting a token via JWT.

Here is the current working code (borrowed from JWT login example from cypress examples):

let user;
before(function() {
  cy.request("POST", Cypress.env("auth_url"), {
    username: Cypress.env("auth_username"),
    password: Cypress.env("auth_password")
  })
    .its("body")
    .then(res => {
      user = res;
    });
});
beforeEach(function() {
  console.log(cy.get_auth_token)
  cy.visit("/", {
    onBeforeLoad(win) {
      // set the user object in local storage
      win.localStorage.setItem("token", user.token);
    }
  });
});

So i tried to do something similar via:

Cypress.Commands.add("get_auth_token", () => {
    let user;
    cy.request("POST", Cypress.env("auth_url"), {
        username: Cypress.env("auth_username"),
        password: Cypress.env("auth_password")
      })
        .its("body")
        .then(res => {
          user = res;
        });
    return user;

})

However when I try to call it within my beforeEach function as let user = cy.get_auth_token I get errors about user being undefined. Am I doing something wrong with returning the value? Im not an expert at promises...but this feels like it should be working?

Thanks!

Questioner
msmith1114
Viewed
69
eric99 2020-02-03 11:23

Commands are not like functions, the return value is not assignable to a local variable. Instead they 'yield' it to the next command in the chain, which can be a then(). Also, the value is a 'subject' which is a jquery-wrapped version of the return value.

In short, this should be how you use your custom command:

beforeEach(function() {
  cy.get_auth_token().then($user => {
    console.log($user[0]);
    cy.visit("/", {
      onBeforeLoad(win) {
        // set the user object in local storage
        win.localStorage.setItem("token", $user[0].token);
      }
    });
  });
});