未能通过使用Cypress的XHR请求测试



大家好,我是柏树的新手,我正在努力通过XHR测试,但我失败了。我做错了什么?

这是我的:

Request URL: http://example.com/api/customer
Request Method: POST
Status Code: 200 OK

以下是我的应用程序在成功请求后的路线:

http://example.com/main/dasboard

这是我的Cypress测试:

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??我也试着只是/客户,但测试失败了,出现了这个错误:

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.route((之后和cy.wait((.之前启动

它是这样工作的:

it.only("Waiting for server response", () => {
cy.server();
cy.route("POST", "**/api/customer").as("dataGetFirst");
// Do something here to trigger the request!
cy.wait("@dataGetFirst").its("status").should("be", 200);
});

如果你升级到Cypress的最新版本,你会想使用cy.entercept((:

it.only("Waiting for server response", () => {
cy.intercept("POST", "**/api/customer").as("dataGetFirst");
// Do something here to trigger the request!
cy.wait("@dataGetFirst").its("status").should("be", 200);
});

这是通过使用cy.request((:解决的

cy.request({
method: 'GET',
url: 'http://example.com/api/customer',
failOnStatus: false
}).then((resp) => {
expect(resp.status).to.eq(200)
})

服务器和路由都被降级了,我也遇到了同样的问题,下面是解决方案:

cy.intercept(
{
method:'GET',
url:'/api/channels/e5932cce
}).as('loginLoaded')

cy.get("@loginLoaded").then((xhr) => {
cy.wait('@loginLoaded').its('response.statusCode').should('eq', 200)
})

最新更新