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.
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");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With