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

查看:28
本文介绍了如何在 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}`);
        });
    });
    

    或(通过 Cypress 的 .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天全站免登陆