7

Assuming I have these test cases (with jest and 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)
  })
})

I want to wait for first test to finish before running the second one (because the first one creates a Actor and the second one ask the API for the created Actor). Running this code fails because the actor is not already created.

Is there a way to wait for the first test to finish before calling the second one?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
rap-2-h
  • 30,204
  • 37
  • 167
  • 263

1 Answers1

10

is just a wrapper over , and in many cases it relies on jasmine's rules.

Therefore, you can make use of the same done callback that is passed to the test function:

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();
})

You can read more about that in jest's async documentation

Adelin
  • 7,809
  • 5
  • 37
  • 65