javascript - 如何使用 Chai 和 mocha 在 Async await Node.js 单元测试代码中强制通过测试用例
问题描述
我正在使用下面的测试用例来测试 Mocha 和 Chai 中的服务,它工作正常。
describe('Google ', () => {
it('POST: Google.', async () => {
const results = await readGoogle.execute(jmsPayload);
console.log(`Final Result : ${results.toString()}`);
});
});
对于上述代码,我需要处理一种情况。实际上我有时会从服务类 readGoogle.execute 方法中得到这个异常。
TypeError: Cannot read property 'status' of undefined
这是从 readGoogle.execute 方法的角度来看的。但我的要求是我需要通过上述测试用例,即使我从 readGoogle.execute await 方法中得到错误。
1)我无权访问 readGoogle.execute 方法,所以我无法处理那里的未定义检查。仅在我的测试用例中要做的任何事情。
return true,
2)我在上面尝试过,'it'
但测试用例仍然失败。
3)我也试过了,断言(真);在上面it
,但测试用例仍然失败。
任何人都可以向我建议一些我可以始终通过上述 test_case 的想法(即使在成功和失败的情况下)?
提前致谢。
解决方案
据我了解,您对上面的readGoogle.execute调用进行了测试,并且由于它是外部资源/api,因此有时会出现异常,这是正确的行为。
在这种情况下,我建议将此调用包装在 try-block 中。
describe('Google ', () => {
it('POST: Google.', async () => {
try {
const results = await readGoogle.execute(jmsPayload);
console.log(`Final Result : ${results.toString()}`);
//maybe some other assertion here about result object.
} catch (e) {
assert.equal(e.name, 'TypeError');
}
});
});
或者在 catch 中做出一些其他断言,以确保这正是您预期的错误。
推荐阅读
- dockerfile - 如何在字符串 docker 中使用环境变量
- python - 我可以在 TRY 和 EXCEPT 子句中添加 IF 子句吗
- python - python-binance order_limit_buy() APIError(code=-1013): Filter failure: LOT_SIZE
- java - org.hibernate.tool.schema.spi.CommandAcceptanceException:执行 DDL 创建表索引时出错
- r - 根据条件创建新列
- web-services - 使用 API 在 adobe connect 中获取所有会议参与者的信息
- python - 有没有办法知道是否使用 Python 在 Windows 中弹出特定窗口?
- python - Python中的编译进度指示
- node.js - 为什么要将二进制数据加密解密为Base64
- python - 在 Seaborn/Pandas 中将 X 轴值更改为星期几(周一 - 周日)