【发布时间】:2017-06-27 10:31:47
【问题描述】:
我目前正在为我的项目编写一些测试脚本。代码用 ES7 编写,编译使用babel
先介绍一下背景:
假设您运行npm test,测试文件如下所示:
function foo (bar) {
if (!bar) throw new Error('foooo')
console.log(bar)
}
foo() // No argument given
现在,当您运行此脚本时,npm 将向您显示如下错误:
$ npm ERR! Test failed. See above for more details.
这是想要的输出,出了点问题,你还不想发布这个软件,因为那里有错误。
那么我的问题是什么?
好吧,我有一个这样的测试脚本设置:
async function init () {
const status = await someRequestPromise()
if (status.error) throw status.error
console.log(status.result) // Log the result of this async request...
}
init()
为了首先运行我的测试,我使用 babel 编译 ES7,如下所示:
$ babel src -d dist
然后运行npm test
结果
我也尝试了以下代码,但这并没有改变任何东西......
async function init () {
const status = await someRequestPromise()
if (status.error) throw status.error
console.log(status.result) // Log the result of this async request...
}
try {
init()
} catch (e) {
console.log(e)
}
我想知道如何触发 npm 来捕获错误并报告测试失败的事实。另外我想知道如何捕获错误,因为节点现在将它们标记为未处理,即使使用 try catch 块也是如此。
PS。在init()函数前面添加await语句会导致语法错误,请不要这样做。
【问题讨论】:
-
默认情况下,
npm test不做任何事情。您正在使用什么测试运行程序/框架?其中许多支持异步测试,例如摩卡可以。 -
npm 捕捉到脚本因未处理的错误而退出的事实。对吗?
-
对不起,忘了说。 @pavlo
标签: javascript node.js npm async-await babeljs