问题描述
我正在从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:
-
嵌套命令:
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调用中将变量用作参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!