Reputation:
Hi people I am new to cypress and I am trying to pass the XHR test but I am failing. What am I doing wrong?
Here are my:
Request URL: http://example.com/api/customer
Request Method: POST
Status Code: 200 OK
Here is my route where my app goes after successful Request:
http://example.com/main/dasboard
Here is my Cypress test:
it.only("Waiting for server response", () => {
cy.server();
cy.route("POST", "**/api/customer").as("dataGetFirst");
cy.wait("@dataGetFirst").its("status").should("be", 200);
});
On my understanding I have to use the request ending api/customer or I need to use /main/dashboard ?? I also tried to just /customer but test is failing with this error:
Timed out retrying: cy.wait() timed out waiting 5000ms for the 1st request to the route: dataGetFirst. No request ever occurred.
UPDATE:
user Alapan Das suggested me to run this code:
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);
});
});
And my test passed, it appears that somehow my method is accepting GET method instead of POST and I will accept it as a solution for my question.
Please note, that here to describe my problem I am using a http://example.com/api/customer
as an example which is not my real test case
Upvotes: 1
Views: 2922
Reputation: 1
Server and routes are depricated, I have had the same problem, here is the solution:
cy.intercept(
{
method:'GET',
url:'/api/channels/e5932cce
}).as('loginLoaded')
cy.get("@loginLoaded").then((xhr) => {
cy.wait('@loginLoaded').its('response.statusCode').should('eq', 200)
})
Upvotes: 0
Reputation: 486
I see you have a different approach now, but to address your initial issue I believe your problem was that you never initiated the request.
The request must be initiated after the cy.route() and before the cy.wait().
It works like this:
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);
});
And if you upgrade to the latest version of Cypress you'll want to use cy.intercept() instead:
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);
});
Upvotes: 2
Reputation: 18634
This was solved by using cy.request():
cy.request({
method: 'GET',
url: 'http://example.com/api/customer',
failOnStatus: false
}).then((resp) => {
expect(resp.status).to.eq(200)
})
Upvotes: 0