如何使用Chai.should

时间:2016-03-25 08:55:39

标签: javascript unit-testing ecmascript-6 chai

我正在使用Chai.should,我需要测试一个例外,但无论我尝试什么,我都无法让它工作。 docs仅解释expect :(

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

会抛出一个错误
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');

这些都不起作用。这是怎么做到的?有什么建议吗?

2 个答案:

答案 0 :(得分:8)

这里的问题是你正在直接执行这个函数,有效地阻止了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为您处理函数调用。

答案 1 :(得分:3)

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

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

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

与接受的答案并没有什么不同,我觉得它更具可读性,更符合他们的指导原则。

相关问题