如何测试与Chai.should抛出错误 [英] How to test for thrown error with Chai.should

查看:235
本文介绍了如何测试与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.

这篇关于如何测试与Chai.should抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆