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, ); } }); });
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.