search

Home  >  Q&A  >  body text

Test does not throw error when expected value is inside loop

I'm trying to refactor some unit tests but found that expect inside a loop doesn't work. I'm looping through an enum. I have the following code:

Are there any solutions or workarounds?

it('should block approval of ads if status is not in pending revision', async () => {
  mockAdsRepository.findOne = jest.fn(() =>
    Promise.resolve({ ...adsDto, status: Status.REJECTED }),
  );
  await expect(service.approve(1, 1)).rejects.toThrow(BadRequestException);

  mockAdsRepository.findOne = jest.fn(() =>
    Promise.resolve({ ...adsDto, status: Status.UNPUBLISH }),
  );
  await expect(service.approve(1, 1)).rejects.toThrow(BadRequestException);

  // error trigger, working
  // mockAdsRepository.findOne = jest.fn(() =>
  //   Promise.resolve({ ...adsDto, status: Status.PENDING_REVISION }),
  // );
  // await expect(service.approve(1, 1)).rejects.toThrow(BadRequestException);

  //refactor
  Object.keys(Status).map(async (key) => {
    if (Status[key] !== Status./*changing this value for error triggers not working*/ ) {
      mockAdsRepository.findOne = jest.fn(() =>
        Promise.resolve({ ...adsDto, status: Status[key] }),
      );

      await expect(service.approve(1, 1)).rejects.toThrow(
        BadRequestException,
      );
    }
  });
});

P粉060112396P粉060112396476 days ago636

reply all(1)I'll reply

  • P粉545910687

    P粉5459106872023-09-19 14:50:38

    I think, in your case the problem is that map doesn't handle asynchronous operations, so at the end of the loop there are several promises in a pending state. You should wait for all promises in the map to be resolved/rejected.

    You can use this function to handle all promises.

    export async function mapAsync<T, R>(
      elements: Promise<T>[] | T[],
      mapAction: (arg: T) => Promise<R>,
    ): Promise<R[]> {
      const results: R[] = [];
      for (const element of await Promise.all(elements)) {
        const mappedItem = await mapAction(element);
        results.push(mappedItem);
      }
      return results;
    }

    reply
    0
  • Cancelreply