DEV Community

Victor Magarlamov
Victor Magarlamov

Posted on

1 2

Testing a request with Cypress

Well, we need to test API. With Cypress we can do it easily. But before we start we need to dance.

Dance with a tambourine

There is one flaw in Cypress. Cypress can track XMLHttpRequests only. Requests with fetch type are invisible to Cypress. We cannot intercept or stub them. But there are some recipes how to solve this small flaw. Let's use one of them - "removes window.fetch method and replaces it with a polyfill based on XMLHttpRequest". Go to the cypress/support directory and download the polifil. Now create a "hooks.js" file.

enableFetchWorkaround();

function enableFetchWorkaround() {
  let polyfill;

  before(() => {
    cy.readFile("./cypress/support/unfetch.umd.js").then(content => {
      polyfill = content;
    })
  });

  Cypress.on("window:before:load", win => {
    delete win.fetch;
    win.eval(polyfill);
    win.fetch = win.unfetch;
  });
}

And add import "./hooks" to the index.js file.

Requests Testing

In order to test a request, we need to send the one

cy.request("/posts").as("postsFetch");

or we need to wait until the request is sent.

cy.route({method: "GET", url: "/posts"}).as("postsFetch");

cy.visit("/posts");

cy.wait("@postsFetch")

Time to test what we have.

it("has the right status code", () => {
  cy.get("@postsFetch")
    .its("status")
    .should("equal", 200);
});

it("has the right content-type", () => {
  cy.get("@postsFetch")
    .its("headers")
    .its("content-type")
    .should("include", "application/json");
});

it("has the right number of items", () => {
  cy.get("@postsFetch")
    .its("responseBody")
    .should("have.length", 20);
});

it("has the right item structure", () => {
  cy.get("@postsFetch")
    .its("responseBody")
    .each(item => {
      expect(item).to.have.all.keys("id", "title", "createdAt");    
    });
});

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay