Джест не ждет асин c, прежде чем все закончится - PullRequest
1 голос
/ 06 апреля 2020

Я пытаюсь проверить получение всех пользователей из моего REST API.

describe('GET', () => {
    let userId;

    // Setup create the mock user
    beforeAll(async () => {
      //Create the user
      return await request
          .post(routes.users.create)
          .set('Accept', 'application/json')
          .send(TEST_USER_DATA)
          .then(res => userId = res.body.id)
    })

    // Clean up, deleting all the fake data that we created for this test suite
    afterAll(async () => {
      // Clean up, delete the user we created
     return await request.delete(routes.users.delete(userId));
    })

    it('should get all users', async () => {
      const usersResponse = await request
        .get(routes.users.getAll)
        .set('Accept', 'application/json')
        .expect(200)
        .expect('Content-Type', /json/);
      // Logs an empty array
      console.log(usersResponse.body);

      expect(usersResponse.status).to.equal(200);
      expect(Array.isArray(usersResponse.body)).to.be.true();
    });
});

Но похоже, что мой it() блок не ждет beforeAll() до конца sh, потому что userResponse.body() это просто пустой массив. Но когда я делаю то же самое в Postman (например, создаю фиктивного пользователя, затем получаю всех пользователей, он отображает массив с пользователем, которого мы создали), поэтому проблема определенно не на стороне сервера.

Я уже пытался написать свой блок beforeAll следующим образом:

beforeAll(async () => {
      //Create the user
      return await new Promise((resolve) => {
        request
          .post(routes.users.create)
          .set('Accept', 'application/json')
          .send(TEST_USER_DATA)
          .then(res => userId = res.body.id)
          .then(() => resolve)
        })
    })

И вот так:

beforeAll(async (done) => {
      //Create the user
      request
        .post(routes.users.create)
        .set('Accept', 'application/json')
        .send(TEST_USER_DATA)
        .then(res => userId = res.body.id)
        .then(() => done());
})

Но ни один из них не работал.

РЕДАКТИРОВАТЬ

Как подсказал @jonrsharpe, я немного изменил свой beforeAll, чтобы проверить состояние ответа, и что мы фактически создали пользователя

beforeAll(async () => {
      //Create the user
      return await request
          .post(routes.users.create)
          .set('Accept', 'application/json')
          .send(TEST_USER_DATA)
          .expect(200)
          .then(res => {
              userId = res.body.id;
              // Log the correct user
              console.log(res.body);
          })
})

И блок beforeAll не делает не получается, поэтому создание пользователя само по себе работает нормально.

...