it('should throw an error if no userPreferences found', async () => {
// Mock findOne result
jest
.spyOn(model, 'findOne')
.mockResolvedValueOnce(throwError(new NotFoundException()));
const result = service.getPreferences('123123');
// Assertion
await expect(result).rejects.toThrow('no results');
});
这是我在控制台中遇到的故障错误:
Received promise resolved instead of rejected
Resolved to value: {"_subscribe": [Function init]}
94 |
95 | // Assertion
> 96 | await expect(result).rejects.toThrow('no results');
| ^
97 | });
98 | });
99 |
at expect (../node_modules/expect/build/index.js:128:15)
at Object.<anonymous> (user-preferences/user-preferences.service.spec.ts:96:13)
这是最终所做的:
mockResolvedValue
通过null,在我知道不存在的值service.getPreferences
您遇到的问题是由于使用ThrowerRor对无染色值的使用不正确。取而代之的是,您应该使用MockejectedValueonce模拟拒绝的承诺。此外,您可以使用try-catch块来处理承诺拒绝并验证错误消息。 我做的对我有用的事情类似:
it('should throw an error if no userPreferences found', async () => {
// Mock findOne result
jest
.spyOn(model, 'findOne')
.mockResolvedValue( null );
// Assertion
expect(service.getPreferences('-1')).rejects.toThrow('no results');
});
MockRejectedValueonce:
嘲笑使用NotFoundException拒绝的FindOne方法。 try-catch块:尝试执行 getPreathences方法并捕获了被扔的任何错误。
expect(e.message)。 错误的消息等于“无结果”。
这种方法可确保如果承诺未按预期拒绝并正确检查错误消息,则测试将失败。