断言使用new执行构造函数时抛出错误

Assert an error is thrown using the new to execute a constructor function

本文关键字:出错 错误 构造函数 执行 new 断言      更新时间:2024-06-29

使用Chai和Mocha,当使用new关键字执行构造函数时,我会使用什么语法来断言抛出了错误?当我使用以下内容时,我会出现错误:

assert.throw(new SomeFunction, Error);

返回:

AssertionError: expected { Object () } to be a function

将函数传递给assert.throw:

assert.throw(function () {
    new SomeFunction()
}, Error);

您没有工作的原因是new SomeFunction被解释为new SomeFunction(),并且在assert.throw执行之前执行。因此,运行assert.throw的对象是SomeFunction的实例,而不是实例化对象的函数。

相关文章: