【问题标题】:How to handle UnhandledPromiseRejectionWarning in simple Mocha Unit Tests如何在简单的 Mocha 单元测试中处理 UnhandledPromiseRejectionWarning
【发布时间】:2018-09-14 14:20:09
【问题描述】:

简单的 mocha,nodejs 单元测试问题。我有一个简单的实用程序类,使用 fs-extra 从本地 fs 读取文件。该类称为 FileUtils,采用路径并尝试默认返回上下文 ion utf-8。简单:

async readFileContent(fqFileName, encoding='utf-8'){
        return fse.readFile(fqFileName,encoding)
            .then(content => content)
            .catch(any=>{
                throw any
            })
    }

我的单元测试只需要类 FileUtils 并通过调用来调用方法

it.only('accepts an html template to compile', () => {
    let fixture = path.resolve(__dirname, '../_fixtures/100_tplWithDynamicBlocks.html')
    fileUtils.readFileContent(fixture)
        .then(content => {
            console.log(content) /* forget */
            content.should.not.be.null
        })
})

工作正常,一切正常。但是,当我将路径更改为无效/不存在的路径时,mocha 并没有意识到错误,只是警告我,未处理的承诺拒绝将在未来退出节点进程。

所以我的问题是,我如何告诉 mocha 这个测试应该被标记为失败而不实现任何类型的 catch 签名,或者更好地我应该如何实现 mocha 识别丢失文件(或其他)访问的服务方法。

服务实现必须抛出不存在路径的错误(或任何其他错误),但是在不编写 mocha-framework 已经在做的不必要代码行的情况下将这些错误传递给 mocha 的最佳方法是什么?

【问题讨论】:

  • ``` (node:13723) UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝 id:1):错误:ENOENT:没有这样的文件或目录,打开 '/Users/Shared/devel/ais/ais -kernel-all/ais-kernel-cce-mailer/srv/test/unit/ais/ccm/_fixtures/100_tplWithDynamicBlocks.html' (node:13723) DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。 2018 年 4 月 4 日星期三 21:20:38 GMT mocha:runner 完成运行```
  • 尝试将.catch(err => console.log(error)); 添加到fileUtilsthen 函数中。

标签: node.js promise async-await mocha.js


【解决方案1】:

你可以在 then 之后使用 catch 方法处理错误。在方法内部你可以写断言。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-30
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    相关资源
    最近更新 更多