3
votes

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.

2
"Localhost should be the same location." — http://localhost and http://localhost:8080 are not the same origin.Quentin
It is not a duplicate because I am not asking what the CORS error means. I am asking why Cypress is handling my test in a way that results in this error. I made this now clearer in my question. Your first comment was a good hint. Thank you.HerrLoesch

2 Answers

19
votes

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:

  • Display insecure content
  • Navigate to any superdomain without cross origin errors
  • Access cross origin iframes that are embedded in your application.
2
votes

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.