Reputation: 1043
I try to simply request data from a route within a cypress test:
it("Then it works", () => {
cy.server()
cy.route({
method: 'GET',
url: '/users/1',
response: true
})
axios.defaults.headers.common = {
"X-Requested-With": "XMLHttpRequest"
}
axios.get("http://localhost:8080/users/1").then(response => {
console.log(response)
expect(response.body).to.equal(true)
}).catch(error => console.log(error))
})
All I get ist "Error: Request failed with status code 404" thus it seems that the route is not available for axios. In my cypress.json I've configured the base URL as:
{
"baseUrl": "http://localhost:8080"
}
From my point of view it is basically the example from the documentation and I can't figure out why it is wrong. I know, that cypress can only handle XMLHttpRequests, so I configured this for axios and I want to simulate with the acios a call that usually happens within my SPA.
Upvotes: 0
Views: 481
Reputation: 3709
You're making the calls from inside the test, while cy.route
is helpful to intercept the front-end requests. More: remember that (from the Cypress docs)
Cypress commands are enqueued and run asynchronously
What I mean: it's the front-end app that must call axios.get
, not you directly from the test.
You can do:
cy.visit
a page that has axios
globally definedit("Then it works", () => {
cy.server()
cy.route({
method: 'GET',
url: '/users/1',
response: true
})
cy.visit("http://localhost:8000"); // replace it with your working app
cy.window().then(win => {
axios.defaults.headers.common = {
"X-Requested-With": "XMLHttpRequest"
}
axios.get("http://localhost:8080/users/1").then(response => {
console.log(response)
expect(response.body).to.equal(true)
}).catch(error => console.log(error))
})
})
and everything should work. If not, please share a GitHub repo with it and I'll help you with that 😊
Upvotes: 1