Skip to content
Advertisement

Cypress not properly intercepting leaflet map tile calls

I am testing a react-leaflet based application in cypress. To avoid making tons of real maptile requests, I am trying to intercept calls to the mapbox maptile server, and replace with a dummy tile. I do this in my cypress/support.index.js file:

/**
 * Intercept all calls for mapbox tiles and replace with dummy tile
 */
beforeEach(() => {
    console.log("in beforeach");
    cy.intercept("https://api.mapbox.com/**/*", {
        fixture: "images/tile.png",
    });
});

A simple test:

describe("The map", () => {
    it("Tiles should be dummy tiles, not actual tiles", () => {
        cy.visit("http://localhost:3000");
    });
});

I took a look at Mock leaflet resources in Cypress, and this tactic seemed to work for this person. When I run a test, I do see the in beforeach log, so I know its running. However, in my test, I don’t even see calls that leaflet is making to get tiles in the list of network requests. As you see on the left, I only see XHR requests. But when I open up the network tab of the cypress runner, clearly we are calling for the tiles (proprietary stuff covered up):

enter image description here

Why is cypress not even showing the calls being made to get map tiles? Why are the calls not being intercepted, and the tiles replaced with the dummy?

I’m usig Cypress 9.5.2, running Chrome 99, with Leaflet 1.7.1, and NexJS 10.2.0.

Advertisement

Answer

I think you might be getting map tiles from cache, at least that’s what I found trying out the intercept on my project.

See Cypress intercept problems – cached response

The server determines the data “cache key” in this case by looking at the if-none-match request header sent by the web application.

Try this to disable caching

cy.intercept('https://api.mapbox.com/**/*', req => {
  delete req.headers['if-none-match'];
  req.reply({
    fixture: 'images/tile.png'
  })
})

The above kind of worked and then it didn’t, and I can’t get my head around it.

As an alternative, you can flick the switch in devtools as follows

cy.wrap(Cypress.automation('remote:debugger:protocol', {
  command: 'Network.clearBrowserCache',
}))

cy.intercept("https://api.mapbox.com/**/*", {
  fixture: "images/tile.png",
})
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement