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 withfetch
type are invisible to Cypress. We cannot intercept or stub them. But there are somerecipes 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 thecypress/support
directory and download thepolifil. Now create a "hooks.js" file.
enableFetchWorkaround();functionenableFetchWorkaround(){letpolyfill;before(()=>{cy.readFile("./cypress/support/unfetch.umd.js").then(content=>{polyfill=content;})});Cypress.on("window:before:load",win=>{deletewin.fetch;win.eval(polyfill);win.fetch=win.unfetch;});}
And addimport "./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)
For further actions, you may consider blocking this person and/orreporting abuse