【问题标题】:NodeJS - Assertion in callback function not failing Mocha unit testNodeJS - 回调函数中的断言没有失败 Mocha 单元测试
【发布时间】: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


【解决方案1】:

在回调中进行断言时,您应该使用 mocha 的 done 回调。 Done 回调将错误作为第一个参数,因此将断言包装在 try/catch 块中以便在断言失败时获得有意义的错误是有意义的:

describe('PDF manipulation', () => {
  it('Manipulated test file should not be null', (done) => {
    fs.readFile('test.pdf', async function (err, data){
      if (err) throw err;
      let manipulatedPdf = await manipulate_file(data);
      try {
        expect(manipulatedPdf).to.be.not.null;
        done()
      } catch (err) {
        done(err)
      }
    });
  });
});

【讨论】:

    猜你喜欢
    • 2020-06-04
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 2021-12-31
    • 1970-01-01
    相关资源
    最近更新 更多