javascript - 如何从柏树测试中调用 fetch?

标签 javascript cypress

我正在使用 Cypress .我有一个小 React 应用程序和一个小 Flask 后端。我希望我的测试调用后端以设置它将要运行的状态。我用的是抓取。这很好用。除了 Cypress 很生气并且不认为测试成功。我真的不是 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")
        })

这似乎工作得很好。但最后,有一个 CypressError:

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

我也尝试过不使用 async/await 并在获取后将步骤放在 then 中,但这没有帮助。将 done 传递给 it block 并在结束时调用 done() 使其不运行任何东西。这是有道理的,因为 Cypress 步骤看起来是同步的,但实际上不是,所以它会在执行任何步骤之前命中 done()

使传递给 it 的函数不是异步的,并将 fetch 更改为

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

而不是 fetch 似乎有效,但我想了解原因。

最佳答案

使用 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");

});

关于javascript - 如何从柏树测试中调用 fetch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63457717/

相关文章:

javascript - jQuery 获取所选类的总标记

javascript - 如何从javascript中的字符串替换(/"or/')到( "or ')

javascript - Cypress Js Testing 将 DOM 的内容与其之前的值进行比较

angular - Cypress 在单独的测试中两次触发 cy.wait(1000)

javascript - dom 元素属性上的 cypress 选择器

parallel-processing - 有没有办法在所有 "x".spec 文件运行后运行指定的 .spec 文件?柏

javascript - 使用自定义函数的传递参数创建对象

javascript - 表单删除文件asp

javascript - 多条件过滤

json - 如何在 cypress 中的 json 中追加新的键值对