DEV Community

Victor Magarlamov
Victor Magarlamov

Posted on

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");    
    });
});

Top comments (0)