如何测试与Chai.should抛出错误

如何测试与Chai.should抛出错误

问题描述:

我正在使用 Chai.should ,我需要测试一个例外,但无论我尝试,我不能让它上班。 文档只解释期望 :(

I'm using Chai.should and I need to test for an exception, but whatever I try, I cannot get it to work. The docs only explain expect :(

我有这个Singleton类,如果您尝试

I have this Singleton class which throws an error if you try

new MySingleton();

这是抛出错误的构造函数

Here is the constructor that throws the error

constructor(enforcer) {
    if(enforcer !== singletonEnforcer) throw 'Cannot construct singleton';
    ...

现在我想检查这是否发生

Now I would like to check that this happens

 it('should not be possible to create a new instance', () => {
    (function () {
        new MySingleton();
    })().should.throw(Error, /Cannot construct singleton/);
 });

new MySingleton().should.throw(Error('Cannot construct singleton');

这些都没有工作,这怎么做?有什么建议? / p>

None of these work. How is this done ? Any suggestions ?

这里的问题是您正在直接执行函数,有效防止chai无法包装尝试{} catch(){} 阻止它。

The Problem here is that you are executing the function directly, effectively preventing chai from being able to wrap a try{} catch(){} block around it.

在调用甚至达到应该 -Property。

The error is thrown before the call even reaches the should-Property.

尝试这样:

 it('should not be possible to create a new instance', () => {
   (function () {
       new MySingleton();
   }).should.throw(Error, /Cannot construct singleton/);
});

或此:

MySingleton.should.throw(Error('Cannot construct singleton');

这让Chai处理函数调用。

This lets Chai handle the function call for you.