Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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 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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Joined

More fromVictor Magarlamov

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp