我试图测试一个异常被抛出,我一直得到这个错误。我觉得我错过了什么。我有这个函数:
async getPreferences(eUserId: string): Promise<UserPreferences> {
const userPreferences = await this.userPreferencesModel.findOne({
eUserId,
});
if (!userPreferences) {
throw new NotFoundException('no results');
}
return userPreferences;
}
这是我的测试:
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
I中传递一个我知道不存在的值
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');
});