如何在Cypress中的API调用中将变量用作参数 [英] How to use a variable as a parameter in an API call in Cypress

查看:930
本文介绍了如何在Cypress中的API调用中将变量用作参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从API调用中捕获一个值并将其设置为变量.我现在想在第二个API调用中将该变量用作URL参数.对于很多人来说,这可能是非常简单的,但是我只是开始学习JavaScript,而我正在阅读和尝试的所有内容都不适合我.非常感谢您能提供的任何帮助,如果您愿意,我很乐意补充细节!

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!

推荐答案

这已经被回答了很多次(我至少给出了两个类似的答案此处).

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

您基本上可以做两件事:

You can basically do two things:

  1. 嵌套命令:

  1. nest the commands:

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

  • 或者,如果您不喜欢回调地狱,则有很多模式.这是三个:

  • or, if you don't like callback hell, there are many patterns. Here's three:

    (请注意,在以下示例中,您不会像上图所示的嵌套那样获得任何东西,因为所有这些示例都至少嵌套一次.但是在您需要嵌套更多的情况下,这些模式仍然是更可取的不止一次,或者如果您需要在测试的稍后阶段重用该变量,并且不想将所有命令都放入第一个回调中).

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

    或(通过赛普拉斯的.as()抽象使用mocha上下文):

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

    或(直接使用mocha上下文):

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

  • 这篇关于如何在Cypress中的API调用中将变量用作参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆