javascript - 赛普拉斯请求是异步的——但是新对象的创建呢?
问题描述
我尝试使用赛普拉斯执行请求,然后使用作为响应接收到的值创建新对象,但是会立即创建新对象,并且在创建所有对象后发送请求:
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.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 毫秒打印一次到控制台,我想这是因为测试是异步的,我在这里尝试使用同步方法。我对么?
解决方案
因为它是异步的,所以您必须保持链接命令以将它们排队。赛普拉斯确实会等待命令(承诺)完成,但前提是您使用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");
});
}
}