typescript - 使用 UnhandledPromiseRejectionWarning 进行测试但通过
问题描述
我正在测试 xml2js 是否返回与预期相同的 JS。如果我在期望值等于接收到的值时运行代码,则不会出现错误。但是,如果我在存在差异时运行代码,我会得到:
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 7.199 s, estimated 8 s
Ran all test suites matching /create/i.
console.error
expect(received).resolves.toEqual(expected) // deep equality
所以控制台能够告诉我有什么问题,但测试套件认为一切正常。
it('converts xml to JS', async () => {
try {
fs.readFile(__dirname + '/' + bpmnxml, 'utf8', async (err, data) => {
if (err) {
console.error(err);
} else {
try {
await expect(parseXML(data)).resolves.toEqual(bpmnjson);
} catch (errExpect) {
console.error(errExpect.message);
// eslint-disable-next-line jest/no-try-expect
// return expect(errExpect).toEqual(new Error('error on expect'));
}
}
});
} catch (errReadFile) {
console.error(errReadFile);
}
});
如果我取消注释,// return expect(errExpect).toEqual(new Error('error on expect'));
那么我会收到另一个错误:
(node:28424) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:28424) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
但是测试套件仍然说它通过了。
我能做些什么来强制错误(这样我得到一个测试失败)但我没有得到这个UnhandledPromiseRejectionWarning
?try-catch 块没有处理这个问题。
解决方案
它可能与 相关fs.readFile
,因为它的同步版本对我有用:
it('converts xml to JS', async () => {
const data = fs.readFileSync(__dirname + '/' + bpmnxml, 'utf8');
expect.hasAssertions();
await expect(parseXML(data)).resolves.toEqual(bpmnjson);
});
当它们应该相等时:
√ converts xml to JS (16 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3.069 s, estimated 4 s
当我对其中一个进行随机更改时:
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 3.247 s, estimated 4 s
推荐阅读
- firebase - 仅更新 Firebase 中字符串的一部分
- python - Find the max length of list inside another list in a dictionary
- swift - 在访问 URL 路径 Swift 时删除部分字符串
- php - 致命错误:未捕获的类型错误:传递给 DOMNode::appendChild() 的参数 1 必须是 DOMNode 的实例,字符串在
- node.js - 如何在 for 循环中运行猫鼬查询并使 res.render 等待
- python - 将 MySQL 结果插入现有的 pandas 数据帧
- python - pipenv 的用例是什么?
- javascript - 如何更改匹配游戏的两个 div 的颜色?
- amazon-cloudwatch - Kinesis Firehose(除了 Kinesis Stream)的任何有用的 Cloudwatch 指标?
- postgresql - PostgreSQL:操作日志