我正在尝试重构一些单元测试,但发现循环内的expect不起作用。我正在遍历枚举。我有以下代码:
有什么解决方案或变通方法吗?
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,
);
}
});
}); Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我认为,在你的情况下问题是map不处理异步操作,所以在循环结束时有几个处于挂起状态的promise。你应该等待map中的所有promise被解决/拒绝。
你可以使用这个函数来处理所有的promise。
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; }