如何从 cypress 测试中调用 fetch?

ohn*_*ain 3 javascript cypress

我正在使用赛普拉斯。我有一个小的 React 应用程序和一个小的 Flask 后端。我希望我的测试能够调用后端来设置它将要运行的状态。我用的是抓取。这很好用。但赛普拉斯很生气,并不认为测试成功。我真的不是一个 javascript 开发人员,所以这可能是显而易见的,但我不知道如何让它快乐。

这是我的测试代码:

    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")
        })
Run Code Online (Sandbox Code Playgroud)

这似乎工作得很好。但最后出现了 CypressError:

Cypress command timeout of 4530ms exceeded. (and Mocha's done() called multiple times)
Run Code Online (Sandbox Code Playgroud)

我还尝试不使用 async/await 并将步骤放入thenafter fetch 中,但这没有帮助。传递done到 it 块并done()在其末尾调用使其不运行任何内容。这是有道理的,因为 cypress 步骤看起来是同步的,但实际上并非如此,因此它会done()在执行其中任何一个之前就已经命中。

使函数传递为非it异步并将 fetch 更改为

Cypress command timeout of 4530ms exceeded. (and Mocha's done() called multiple times)
Run Code Online (Sandbox Code Playgroud)

而不是fetch似乎有效,但我想了解为什么。

小智 5

使用cy.request而不是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");

});

Run Code Online (Sandbox Code Playgroud)