How to mock the image response in cypress

Viewed 1758

My problem

I'm trying to simulate a response from the server containing an image with cy.intercept however, the browser won't display my mocked image. The browser just can't interpret my response as a proper image for <img> tag.

debug tools screenshot

I can still copy the response in debug tools and it seems to be the image I need but probably encoded in the wrong way.

My approach

    cy.readFile('src/assets/logo.png', 'binary').then((imgContent) => {
      cy.intercept('/uploads/test.png', {
        headers: { 'Content-Type': 'image/jpg' },
        body: imgContent,
      })
    });

I've also tried to return base64 image string like this:

    cy.intercept(
      '/uploads/test.png',
      {
        headers: {"Content-Type": "image/jpg"},
        body:
      'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAARCUlEQVR4Xu1deXQURRr...

But it didn't work as well.

1 Answers

This seems like a job for a fixture

cy.intercept("/uploads/test.png", { fixture: "logo.png" })

By default, you would place your logo.png file into the cypress/fixtures directory however you can configure it to use another location

Related