我尝试使用柏树执行请求,然后创建新的对象,并在响应中收到的值,但立即创建了新对象,并且在所有对象已经创建后,请发送请求:
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"one_answers" 5"。但是,我几乎立即得到" 1"," 3"," 4"one_answers" 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代码"像每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");
});
}
}