gpt4 book ai didi

javascript - Jest : Wait for an async test to finish before running the next one

转载 作者:搜寻专家 更新时间:2023-10-31 23:03:07 28 4
gpt4 key购买 nike

假设我有这些测试用例(使用 jestsupertest):

describe('Test actors', async () => {
const params = { /* ... */ }
let actorId

test(`Create an actor ${actorsUrl}`, async () => {
const response = await request(app.callback())
.post(actorsUrl)
.send(params)
.set('Accept', 'application/json')
.set('Content-Type', 'application/json')
.expect(200)
expect(response.body.name).toBe(params.name)
expect(response.body.address).toBe(params.address)
actorId = response.body.id
})

test(`Get the actor created ${actorsUrl}/${actorsUrl}`, async () => {
const response = await request(app.callback())
.get(`${actorsUrl}/${actorsUrl}`)
.set('Accept', 'application/json')
.expect(200)
expect(response.body.name).toBe(params.name)
expect(response.body.address).toBe(params.address)
})
})

我想在运行第二个测试之前等待第一个测试完成(因为第一个测试创建了一个 Actor 而第二个测试向 API 请求创建的 Actor ).运行此代码失败,因为尚未创建参与者。

有没有办法在调用第二个测试之前等待第一个测试完成?

最佳答案

只是 的包装,并且在许多情况下它依赖于 jasmine 的规则。

因此,您可以利用 the same done callback传递给 test 函数:

test(`Create an actor ${actorsUrl}`, async (done) => {
const response = await request(app.callback())
.post(actorsUrl)
.send(params)
.set('Accept', 'application/json')
.set('Content-Type', 'application/json')
.expect(200)
expect(response.body.name).toBe(params.name)
expect(response.body.address).toBe(params.address)
actorId = response.body.id
done();
})
test(`Get the actor created ${actorsUrl}/${actorsUrl}`, async (done) => {
const response = await request(app.callback())
.get(`${actorsUrl}/${actorsUrl}`)
.set('Accept', 'application/json')
.expect(200)
expect(response.body.name).toBe(params.name)
expect(response.body.address).toBe(params.address)
done();
})

您可以在 jest 的 async documentation 中阅读更多相关信息

关于javascript - Jest : Wait for an async test to finish before running the next one,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51286806/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com