Search code examples
javascriptcypresscy.intercept

How to pass content yielded in cy.wait() to the variable and reuse it in the next steps?


I use cy.intercept() and cy.wait() to listen to the request and yield content from it.

let number;

describe("some test", () => {
  before(() => {
    cy.clearCookies();
  });
  it("some test", () => {
    cy.someCommand();
    clientPage.someMethod();
    cy.intercept("**/request").as("idNumber");
    clientPage.someMethod1();
    cy.wait("@idNumber").then((res) => {
      number = res.response.body.numbers.id
    });
    cy.get(#someELement).type(number)
 });
});

It gives me "cy.type() can only accept a string or number. You passed in: undefined" When I try to log cy.log(number) under "number = res.response.body.numbers.id" it works. When I try to pass the variable out of this code block it is undefined. How can I pass it into the further steps?


Solution

  • To make sure the value of number is passed on to the type, you have to add a then, something like:

    let number
    
    describe('some test', () => {
      before(() => {
        cy.clearCookies()
      })
      it('some test', () => {
        cy.someCommand()
        clientPage.someMethod()
        cy.intercept('**/request').as('idNumber')
        clientPage.someMethod1()
        cy.wait('@idNumber')
          .then((res) => {
            number = res.response.body.numbers.id
          })
          .then(() => {
            cy.get('#someELement').type(number)
          })
      })
    })
    

    If you want to use the variable globally throughout the project, you can use the Cypress.env() method. Cypress Docs.

    describe('some test', () => {
      before(() => {
        cy.clearCookies()
      })
      it('some test', () => {
        cy.someCommand()
        clientPage.someMethod()
        cy.intercept('**/request').as('idNumber')
        clientPage.someMethod1()
        cy.wait('@idNumber').then((res) => {
          cypress.env('number', res.response.body.numbers.id) //Sets Number
        })
        cy.get('#someELement').type(Cypress.env('number')) //Gets Number and types it
      })
    
      it('some different test', () => {
        cy.get('#someELement').type(Cypress.env('number')) //types the number
      })
    })