I would like to mock some of the API calls done by my SPA. Therefor I am using cypress.JS and checked how to do this by using following test.
it("Then it works", () => {
    axios.defaults.baseURL = 'http://localhost';
    
    cy.server()
    cy.route("GET", "http://localhost/users/", true)
    
    axios.get("/users/").then(response => {
        console.log("received response: " + response)
        expect(response.body).to.equal(true)
    }).catch(error => console.log(error))
})
It does not work I get the error "Access to XMLHttpRequest at 'http://localhost/users/' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."
Is there any way to prevent this error during tests? I don’t understand why Cypress is handling this simple test in a way that this error can occure.
In your cypress.json set chromeWebSecurity to false.
{
  "chromeWebSecurity": false
}
As from cypress documentation here, setting chromeWebSecurity to false allows you to do the following:
The issue was, that I configured cypress with base url localhost:8080
{
  "baseUrl": "http://localhost:8080"
}
but used only local host in my test
   it("Then it works", () => {
    cy.server()           
    cy.route({
        method: 'GET',     
        url: '/users/1',    
        response: true        
    })
    axios.get("http://localhost:8080/users/1").then(response => {
        console.log("received response: " + response)
        expect(response.body).to.equal(true)
    }).catch(error => console.log(error))
})
The test is still not working but my initial question is answered. The error occured because the port was missing. I will update this when I found a solution for my other problem.
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