如何使用 Chai.should 测试抛出的错误

How to test for thrown error with Chai.should

我正在使用 Chai.should and I need to test for an exception, but whatever I try, I cannot get it to work. The docs 只解释 expect :(

我有这个 Singleton class 如果你尝试

它会抛出一个错误
new MySingleton();

这是抛出错误的构造函数

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

现在我想检查是否发生了这种情况

 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');

None 这些作品。这是怎么做到的?有什么建议吗?

这里的问题是您正在直接执行该函数,有效地阻止了 chai 将 try{} catch(){} 块包裹在它周围。

错误甚至在调用到达 should-属性 之前抛出。

这样试试:

 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 为您处理函数调用。

我知道这是一个已回答的问题,但我仍然想投入我的两分钱。

样式指南中有一个部分是针对此的,即:http://chaijs.com/guide/styles/#should-extras。那么这在实践中是什么样子的:

should.Throw(() => new MySingleton(), Error);

它与公认的答案并没有什么不同,但我发现它更具可读性,并且更符合他们的指导方针。