ohnonotagain
ohnonotagain

Reputation: 41

How can I call fetch from within a cypress test?

I'm using Cypress. I have a little React app and a little Flask backend. I want my test to make a call to the backend to set up the state it's going to operate on. I used fetch. This works fine. Except Cypress is mad and doesn't consider the test a success. I am not a javascript developer really so this might be obvious, but I can't figure out how to make it happy.

This is my test code:

    it.only("edits a job", async () => {
        const now = new Date().getTime()
        const title = `Edit-This-${now}`
        const newTitle = `SUCCESS-EDIT-${now}`
        const company = `Edit Company-${now}`
        const link = `https://example.com/edit-me-${now}`
        const status = "Edit Test"
        const body = JSON.stringify({company, title, link, status})
        await fetch('/add_job', {method: 'post', headers: {'Content-Type': 'application/json'}, body: body})
        cy.visit("http://localhost:3000/jobs_list")
        cy.contains(title)
        cy.contains(company)
        cy.contains(link)
        cy.contains(status)

        cy.get(`[name=edit-${title}`).click()
        cy.get(`[value=${title}`).clear().type(newTitle)
        cy.get(`[name=save-${newTitle}`).click()

        cy.contains(newTitle)
        console.log("what the heck")
        })

This seems to work just fine. But at the end, there's a CypressError:

Cypress command timeout of 4530ms exceeded. (and Mocha's done() called multiple times)

I also tried not using async/await and putting the steps inside a then after fetch, but that didn't help. Passing done to the it block and calling done() at the end of that made it not run anything. That makes sense because cypress steps look synchronous but are in fact not, so it would have hit done() before executing any of them.

Making the function passed to it not async and changing fetch to

cy.request('POST', 'http://localhost:3000/add_job', {'Content-Type': 'application/json', company, title, link, status})

instead of fetch seems to have worked, but I'd like to understand why.

Upvotes: 4

Views: 11354

Answers (3)

Larry Maccherone
Larry Maccherone

Reputation: 9523

You can use fetch with async/await in cypress tests like this:

it('should do something', () => {
  const originalObject = { a: 1 }
  const options = {
    method: 'PUT',
    body: JSON.stringify(originalObject),
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    },
  }

  cy.wrap(null).then(async () => {
    const response = await fetch('/echo', options)
    const echoedObject = await response.json()
    expect(echoedObject).to.deep.eq(originalObject)
  })
})

Upvotes: 1

Glennweb
Glennweb

Reputation: 139

Use cy.request rather than fetch.

https://docs.cypress.io/api/commands/request

cy.request({yourUri}).as("response"); // This takes care of the async task. 
 
cy.get("@response").should((response) => { 
   // Carry on with the rest of your test
   cy.get("some selector");

});

Upvotes: 8

Cory Danielson
Cory Danielson

Reputation: 14501

https://docs.cypress.io/guides/core-concepts/introduction-to-cypress.html#Chains-of-Commands

It’s very important to understand the mechanism Cypress uses to chain commands together. It manages a Promise chain on your behalf, with each command yielding a ‘subject’ to the next command, until the chain ends or an error is encountered. The developer should not need to use Promises directly, but understanding how they work is helpful!

You can add items to the Cypress promise chain/queue via Cypress.Promise

You could likely wrap your fetch call use Cypress.Promise, but cy.request is recommended for this unless you have some specific reason not to use it.

// wrap null, so that you can use `then` to invoke a callback as an arbitrary command
// and return a Cypress.Promise - so that cypress will wait on it's result
// (or just use cy.request :))
cy.wrap(null).then(() => {
  return new Cypress.Promise((resolve, reject) => {
    try {
      fetch(/*...*/).then(resolve);
    } catch (e) {
      reject(e);
    }
  })
})

Upvotes: 3

Related Questions