在Angular和Jest中,当一个测试通过但应该失败时,出现"未处理的Promise拒绝:expect(received).toEqual(expected)"错误通常是因为在测试中使用了异步操作,并且没有处理异步操作的拒绝情况。
以下是解决这个问题的几种方法:
async
,并使用await
关键字来等待异步操作完成。然后使用try/catch
块来捕获任何可能的拒绝,并在catch块中使用expect().toEqual()
来断言异步操作的结果。it('should fail an async test', async () => {
try {
const result = await asyncFunction();
expect(result).toEqual(expected);
} catch (error) {
expect(error).toEqual(expectedError);
}
});
.catch()
方法:如果使用Promise链式调用,可以在链式调用的末尾使用.catch()
方法来捕获拒绝情况,并在.catch()
中断言异步操作的结果。it('should fail an async test', () => {
return asyncFunction()
.then(result => {
expect(result).toEqual(expected);
})
.catch(error => {
expect(error).toEqual(expectedError);
});
});
.rejects.toEqual()
方法:如果使用了Jest的.rejects
匹配器,可以直接使用.rejects.toEqual()
来断言拒绝的结果。it('should fail an async test', async () => {
await expect(asyncFunction()).rejects.toEqual(expectedError);
});
请注意,这里的asyncFunction()
是一个占位符,你需要将其替换为实际的异步操作函数。
希望这些解决方法能帮助到你解决这个问题!