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

匆匆过客 提交于 2020-01-25 08:20: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 simple for a lot of folks but I'm just starting out learning javascript and everything I'm reading and trying is not working for me. I'd appreciate any help you can offer and I'm happy to add detail if you like!


回答1:


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}`);
        });
    });
    


来源:https://stackoverflow.com/questions/58757793/how-to-use-a-variable-as-a-parameter-in-an-api-call-in-cypress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!