Jest перестает выполнять ожидаемые заявления после первого сбоя - PullRequest
0 голосов
/ 20 января 2020

В тесте у меня есть следующий оператор expect в al oop, который должен выполняться дважды:

expect(nr).toEqual(res.body.items[index]);

На первой итерации, если тест не пройден, однако jest не выполняет l oop снова.

Если я заменю его на тот, который проходит, jest выполняет его для каждой итерации l oop:

expect(nr).toEqual(res.body.items[index]);

Вот код с дополнительным контекстом:

describe('Recipe', () => {
    beforeAll(async () => {});
    beforeEach(async () => {});
    afterEach(async () => {});

    it('should do proper grouping when GET /recipes?filterId=[...]', async () => {
      // setup

      const res = await request(app.getHttpServer())
        .get(...);

      expect(res.status).toBe(200);
      if (res.body.items) {
        [recipeWithProduct1, recipeWithProduct2].forEach((r, index) => {
          console.log('LLL200 testing', index);
          const nr = { ...r, ...{ updatedAt: '', createdAt: '' } };
          delete nr.store;
          delete nr.creator;
          nr.updatedAt = r.updatedAt.toISOString();
          nr.createdAt = r.createdAt.toISOString();
          nr.filters = nr.filters.map(f => f.id) as any; // TODO: fix this coersion

        //   expect(true).toBe(true); // console.log above prints twice if we uncomment this and 
        // comment the expect below
          expect(nr).toEqual(res.body.items[index]); // fails only once
        });
      }
      expect(res.body.total).toEqual(2);
    })
});

Как заставить jest выполнить все ожидаемые операторы, даже если предыдущие не дали результатов?

Я на jest версии 23.6 +0,0.

1 Ответ

1 голос
/ 20 января 2020

Это происходит, потому что внутренне expect выдает ошибки. Чтобы заставить их все работать, вы можете разделить их в разных тестовых случаях.

Вот пример того, как может выглядеть улучшенная версия ваших тестов:

describe('Recipe', () => {
    let res;
    beforeAll(async () => {
      res = await request(app.getHttpServer())
        .get();
    });
    beforeEach(async () => {});
    afterEach(async () => {});

    describe('response', () => {

      describe.each([
        [recipeWithProduct1, 0],
        [recipeWithProduct2, 1]
      ])('receipe %j %#', (receipe, index) => {
        it(`should match res.body.items[${index}]`, () => {
          expect(res.body.items[index]).toEqual(
            expect.objectContaining({
              ...receipe,
              createdAt: receipe.createdAt.toISOString(),
              updatedAt: receipe.updatedAt.toISOString(),
            })
          );
        })
      })

      it('should have status 200', () => {
        expect(res).toHaveProperty('status', 200)
      })

      it('should have body.total', () => {
        expect(res).toHaveProperty('body.total', 2);
      })
    })
});

рабочий пример

...