All of the example I found are with calling the API and defining method and URL. For example
cy.server()
cy.route({
method: 'GET',
url: 'https://www.something.com',
}).as('get_jobs')
cy.get('[data-cy="job-search-input"] button').click()
cy.wait('@get_jobs').then((xhr) => {
cy.log(xhr.response.body.data)
})
What I want is just to select the button, press click and read the response that it gives me. I don't wanna define url and method again, but use the one that is already used in the code and just check the response that it gives me after pressing the button.
How can I do that?
Using cy-api plugin Also, you need to open browser console to look into the details of Cypress response. But with cy-api plugin, the request, as well as response get rendered into browser window, so you can easily observe your APi even in GUI mode. This plugin will add .
To make an XHR request, the cy. request() command is used. The method cy. intercept() is used to redirect the responses to the matching requests.
From the question and the comments above, it sounds like you're trying to do something like this:
While it is possible to write tests in this way, there is a problem with this: the response from the API may change depending on circumstances outside your control. For example, what happens if you're working on your project and the API happens to be down that day? Your code is going to break and it won't be due to a bug in your code. In fact, you won't be testing your code at all (at least not the code you thought you were testing), because you won't be getting the response you want from the API.
This is why Cypress provides a way to stub the requests - to make sure that when your tests are running, you are getting the response you want from the API. If you want to write a test to see what happens when the API returns value A, you need to make sure the API doesn't return value B. Stubbing the requests allows you to make sure the application gets value A when you need it to.
So the examples you've seen probably do something like this:
cy.route
to stub the API requests to return a known valueIf you have a range of different response values for which you want to test your app's behaviour, write a set of tests, one for each value.
If you just want to read the response, you can use onReponse
in cy.server
:
cy.server({
onResponse(response) {
// Log every response
console.log("response", response);
// Using the response URL from OP's question
if (response.url.includes("https://www.something.com")) {
// etc.
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With