Javascript npm测试不';t捕获异步函数中抛出的错误
我目前正在为我的项目编写一些测试脚本。代码是用ES7编写的,并使用Javascript npm测试不';t捕获异步函数中抛出的错误,javascript,node.js,npm,async-await,babeljs,Javascript,Node.js,Npm,Async Await,Babeljs,我目前正在为我的项目编写一些测试脚本。代码是用ES7编写的,并使用babel 首先是一些背景: 假设您运行npm测试,测试文件如下所示: function foo (bar) { if (!bar) throw new Error('foooo') console.log(bar) } foo() // No argument given $ npm ERR! Test failed. See above for more details. async function init
babel
首先是一些背景: 假设您运行
npm测试
,测试文件如下所示:
function foo (bar) {
if (!bar) throw new Error('foooo')
console.log(bar)
}
foo() // No argument given
$ 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()
现在,当您运行此脚本时,npm将显示如下错误:
function foo (bar) {
if (!bar) throw new Error('foooo')
console.log(bar)
}
foo() // No argument given
$ 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()
这是期望的输出,出现了一些问题,您不想发布此软件,因为其中有一个错误
那么我的问题是什么?
好的,我有一个测试脚本设置如下:
function foo (bar) {
if (!bar) throw new Error('foooo')
console.log(bar)
}
foo() // No argument given
$ 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测试
结果 要明确的是,npm没有触发错误 我也尝试了下面的代码,但是这并没有改变任何事情
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块也是如此
注:在
init()
函数前面添加await
语句会导致语法错误,请不要建议这样做。由于async/await
返回承诺,您必须通过处理拒绝(就像控制台输出建议的那样)。catch
:
const handle = init()
handle
.then((result) => handleSuccess(result))
.catch(({message}) => console.log(message))
try/catch
(至少在我的经验中)用于同步代码
编辑:
要使脚本“崩溃”,只需添加一个进程。退出(1)
默认情况下,
npm测试
不执行任何操作。您使用的测试运行程序/框架是什么?它们中的许多都支持异步测试,例如Mocha does.npm捕捉到脚本在未处理错误时退出的事实。对吗?对不起,忘了提了@可能的复制品,还有更多我会调查的。尽管try/catch
阻止了与async/waityes组合的最佳实践,但如果您在异步函数内部而不是外部处理错误,就像它的前身ES6生成器一样。这有意义吗?还有,你在哪里找到了关于try/catch的信息?这些信息是基于我自己的记忆哈哈。有一天在某处读到它。。。(我将快速测试.catch()
方法)好的,是的,虽然这是处理任何错误的理想方法,但它仍然不是让npm真正捕获程序失败这一事实的有效方法。您正在处理错误,因此预计。。。脚本不会崩溃。只需添加进程。在catch
部分退出(1)