Search code examples
javascriptnode.jsunit-testingjestjssupertest

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


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?


Solution

  • 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