我尝试使用 Cypress 执行请求,然后使用响应中收到的值创建新对象,但是新对象是立即创建的,并且在所有对象都已创建后才发送请求:
describe("example", function() {
it("of test", function() {
console.log("1");
cy.request({
url: Cypress.env("URL"),
method: "POST",
headers: auth_req.authHeaders,
body: merged_body
})
.as("/authorize")
.then((resp) => {
console.log("2");
Cypress.env("resp_code", resp.status);
console.log("RESP CODE FROM RESPONSE:");
console.log(resp.status);
})
.its("headers")
.its("content-type")
.should("include", "application/json");
console.log("3");
const var1 = new something.NotImportant;
console.log("4");
const var2 = new something.AlsoNotImportant;
console.log("5");
}
}
我希望在控制台中得到“1”、“2”、“3”、“4”和“5”。但是,我几乎立即得到“1”、“3”、“4”和“5”,几秒钟后(服务器响应缓慢)我看到请求正在发送,“2”正在吐出到我的控制台。
我的问题是:如果我理解正确,请求是异步的,Cypress 正在等待它们完成,那么为什么测试不等待接收响应然后创建对象?我如何修改代码以确保我想要在请求之后创建的对象使用在创建新对象期间从请求中收到的值?我尝试使用 Cypress.env,但对象是在请求之前创建的,并且使用了不正确的值而不是从响应中读取的值。
奖金问题:为什么这段代码没有按预期工作(挂起计算机)?
while (true) {
cy.wait(5000);
var resp_code = Cypress.env("resp_code");
console.log("RESP CODE:");
console.log(Cypress.env("resp_code"));
}
“RESP CODE”每 100 毫秒打印一次到控制台,我想这是因为测试是异步的,我在这里尝试使用同步方法。我说得对吗?
最佳答案
因为它是异步的,所以您必须保持链接命令以将它们排队。 Cypress 确实会等待命令( promise )完成,但前提是您使用 then()
告诉它。
您可以这样做:
describe("example", function() {
it("of test", function() {
console.log("1");
cy.request({
url: Cypress.env("URL"),
method: "POST",
headers: auth_req.authHeaders,
body: merged_body
})
.as("/authorize")
.then((resp) => {
console.log("2");
Cypress.env("resp_code", resp.status);
console.log("RESP CODE FROM RESPONSE:");
console.log(resp.status);
console.log("3");
const var1 = new something.NotImportant;
console.log("4");
const var2 = new something.AlsoNotImportant;
console.log("5");
})
.its("headers")
.its("content-type")
.should("include", "application/json");
}
}
或者这个:
describe("example", function() {
it("of test", function() {
console.log("1");
cy.request({
url: Cypress.env("URL"),
method: "POST",
headers: auth_req.authHeaders,
body: merged_body
})
.as("/authorize")
.then((resp) => {
console.log("2");
Cypress.env("resp_code", resp.status);
console.log("RESP CODE FROM RESPONSE:");
console.log(resp.status);
})
.its("headers")
.its("content-type")
.should("include", "application/json")
.then(() => {
console.log("3");
const var1 = new something.NotImportant;
console.log("4");
const var2 = new something.AlsoNotImportant;
console.log("5");
});
}
}
关于javascript - Cypress 请求是异步的——但是新对象的创建呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56325900/