开玩笑:在运行下一个测试之前,请等待异步测试完成

时间:2018-07-11 13:32:01

标签: javascript node.js unit-testing jestjs supertest

假设我有以下测试用例(使用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)。运行该代码失败,因为尚未创建actor。

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

1 个答案:

答案 0 :(得分:5)

只是的包装,在许多情况下,它依赖于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

中了解更多相关信息