Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

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

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...