代码之家  ›  专栏  ›  技术社区  ›  rap-2-h

杰斯特:在运行下一个异步测试之前,请等待异步测试完成。

  •  3
  • rap-2-h  · 技术社区  · 6 年前

    假设我有这些测试用例 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

    1 回复  |  直到 5 年前
        1
  •  5
  •   Adelin    5 年前

    只是包装纸而已 在许多情况下,它依赖于 jasmine 的规则。

    因此,你可以利用 the same done callback 传给 test 功能:

    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