【发布时间】:2020-11-27 02:01:40
【问题描述】:
我正在尝试在 NodeJS 应用程序上运行 Mocha 单元测试,但在处理回调函数中的断言时遇到问题。
例如,我有以下单元测试:
describe('PDF manipulation', () => {
it('Manipulated test file should not be null', async () => {
fs.readFile('test.pdf', async function (err, data){
if (err) throw err;
let manipulatedPdf = await manipulate_file(data);
expect(manipulatedPdf).to.be.not.null;
});
});
});
当单元测试运行时,我故意将manipuldatedPdf设为null以验证断言是否有效。
断言比较成功完成,但单元测试显示为通过测试并打印出与未处理的承诺拒绝相关的警告:
(node:13492) UnhandledPromiseRejectionWarning: AssertionError: expected null not to be null
at ...
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:13492) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13492) [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.
从尝试解决问题开始,看起来我需要能够.catch()readFile 的回调函数中引发的任何异常,但在TypeError: (intermediate value).catch is not a function 中添加类似以下结果的内容:
describe('PDF manipulation', () => {
it('Manipulated test file should not be null', async () => {
fs.readFile('test.pdf', (async function (err, data){
if (err) throw err;
let manipulatedPdf = await manipulate_file(data);
expect(manipulatedPdf).to.be.not.null;
}).catch(error => console.log(error)));
});
});
有没有办法处理这些断言失败导致单元测试失败?
【问题讨论】:
标签: javascript node.js unit-testing promise mocha.js