【发布时间】:2021-03-07 23:32:36
【问题描述】:
大家好,我是 cypress 的新手,我正在尝试通过 XHR 测试,但我失败了。 我做错了什么?
这是我的:
Request URL: http://example.com/api/customer
Request Method: POST
Status Code: 200 OK
这是我的应用在请求成功后的路径:
http://example.com/main/dasboard
这是我的赛普拉斯测试:
it.only("Waiting for server response", () => {
cy.server();
cy.route("POST", "**/api/customer").as("dataGetFirst");
cy.wait("@dataGetFirst").its("status").should("be", 200);
});
据我了解,我必须使用请求结束 api/customer 或者我需要使用 /main/dashboard ??我也尝试了 /customer 但测试失败并出现此错误:
Timed out retrying: cy.wait() timed out waiting 5000ms for the 1st request to the route: dataGetFirst. No request ever occurred.
更新:
用户 Alapan Das 建议我运行此代码:
it.only("Waiting for server response", () => {
cy.request({
method: "GET",
url: "http://example.com/api/customer",
failOnStatusCode: false
}).then((resp) => {
expect(resp.status).to.eq(200);
});
});
我的测试通过了,我的方法似乎以某种方式接受 GET 方法而不是 POST,我将接受它作为我问题的解决方案。
请注意,这里为了描述我的问题,我以http://example.com/api/customer 为例,这不是我真正的测试用例
【问题讨论】:
-
你可以试试这个。这将检查您的重定向:
cy.request({ method: 'POST', url: 'http://example.com/api/customer', followRedirect: false // turn off following redirects }) .then((resp) => { // redirect status code is 302 expect(resp.status).to.eq(302) expect(resp.redirectedToUrl).to.eq('http://example.com/main/dasboard') }) -
什么是重定向状态码 302??
-
因为您的 URL 正在重定向到另一个 URL,这就是 302 的原因。您也可以尝试使用 200,因为我不知道您的应用程序在重定向时响应什么 HTTP 状态代码。此外,上面的代码不会重定向您,只会检查重定向。如果您想重定向到
http://example.com/main/dasboard,只需使用followRedirect: true -
两个都试了,现在报404错误
-
我的假设是它没有任何身份验证,而且您使用的是整个 URL 而不是部分 URL,并且当您通过 Postman(或类似工具)点击它时,相同的端点正在工作,并且请求端点不需要请求正文。那你能试试这个吗?
cy.request({ method: 'POST', url: 'http://example.com/api/customer', }) .then((resp) => { expect(resp.status).to.eq(200) })