Test does not throw error when expected value is inside loop
P粉060112396
P粉060112396 2023-09-18 15:34:42
0
1
605

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粉060112396
P粉060112396

reply all(1)
P粉545910687

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;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template