假设我有以下测试用例(使用jest
和supertest
):
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
)。运行该代码失败,因为尚未创建actor。
在调用第二个测试之前,是否有办法等待第一个测试完成?
答案 0 :(得分:5)
jestjs只是jasmine的包装,在许多情况下,它依赖于jasmine
的规则。
因此,您可以利用传递给test
函数的the same done
callback:
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();
})
您可以在玩笑的async documentation
中了解更多相关信息