Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 974
rap-2-h Avatar asked Jul 11 '18 13:07

rap-2-h


1 Answers

jestjs is just a wrapper over jasmine, 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

like image 169
Adelin Avatar answered Nov 14 '22 23:11

Adelin