How to use a variable as a parameter in an API call in Cypress

后端 未结 1 495
猫巷女王i
猫巷女王i 2020-12-12 06:28

I am capturing a value from an API call and have set it to a variable. I would now like to use that variable as a URL parameter in a second API call. This is probably super

相关标签:
1条回答
  • 2020-12-12 07:06

    This has been answered many times before (I gave at least two similar answers here and here).

    You can basically do two things:

    1. nest the commands:

      it('test', function () {
          cy.request().then( resp => {
              return cy.visit(`/path/${response.body}`);
          });
      });
      
    2. or, if you don't like callback hell, there are many patterns. Here's three:

      (note, in following examples you don't gain anything as opposed to nesting as shown above because all these examples nest at minimum once. But these patterns may still be preferable in case you'd need to nest more than once, or if you need to reuse the variable much later in the test and don't want to put all commands into the first callback).

      it('test', function () {
          let value;
          cy.request().then( resp => {
              value = response.body;
          });
          cy.then(() => {
              return cy.visit(`/path/${value}`);
          });
      });
      

      or (using mocha context via Cypress' .as() abstraction):

      it('test', function () {
          let value;
          cy.request().then( resp => {
              cy.wrap(response.body).as('value');
          });
          cy.get('@value').then( value => {
              return cy.visit(`/path/${value}`);
          });
      });
      

      or (using mocha context directly):

      it('test', function () {
          cy.request().then( resp => {
              // store as mocha context
              // (note: in this pattern it's important the test case function is
              //  regular, non-arrow function; and the callback passed to `.then`
              //  is an arrow function so that you have access to parent
              //  lexical context via `this`)
              this.value = response.body;
          });
          cy.then(() => {
              return cy.visit(`/path/${this.value}`);
          });
      });
      
    0 讨论(0)
提交回复
热议问题