测试Mocha中引发的错误 [英] Testing for errors thrown in Mocha

查看:229
本文介绍了测试Mocha中引发的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能找到一些帮助解决这个问题。我正在尝试为我正在编写的应用程序编写测试。我已将问题提炼到以下示例代码中。我想测试一个错误被抛出。我使用Testacular作为测试运行器,mocha作为框架,chai作为断言库。测试运行,但测试失败,因为抛出了错误!非常感谢任何帮助!

I'm hoping to find some help with this problem. I'm trying to write tests for an application I am writing. I have distilled the problem in to the following sample code. I want to test that an error was thrown. I'm using Testacular as a test runner with mocha as the framework and chai as the assertion library. The tests run, but the test fails because an error was thrown! Any help is greatly appreciated!

function iThrowError() {
    throw new Error("Error thrown");
}

var assert = chai.assert,
    expect = chai.expect;
describe('The app', function() {
    describe('this feature', function() {
        it("is a function", function(){
            assert.throw(iThrowError(), Error, "Error thrown");
        });
    });
});


推荐答案

你没有将你的功能传递给 assert.throws()正确的方法。

You're not passing your function to assert.throws() the right way.

assert.throws() function期望函数作为其第一个参数。在您的代码中,您调用iThrowError并在调用 assert.throws()时传递其返回值。

The assert.throws() function expects a function as its first parameter. In your code, you are invoking iThrowError and passing its return value when calling assert.throws().

基本上,改变这个:

assert.throws(iThrowError(), Error, "Error thrown");

到此:

assert.throws(iThrowError, Error, "Error thrown");

应解决您的问题。

这篇关于测试Mocha中引发的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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