测试Mocha中引发的错误

时间:2013-02-19 20:31:51

标签: javascript testing mocha chai

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

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");
        });
    });
});

3 个答案:

答案 0 :(得分:102)

您没有以正确的方式将您的功能传递给assert.throws()

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

基本上,改变这个:

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

到此:

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

应该解决你的问题。

答案 1 :(得分:27)

添加到the top answer,如果需要在测试中调用函数(即,如果传递了某些参数,函数应该只抛出错误),则可以将函数调用包装在匿名函数中,或者,在ES6 +中,您可以使用箭头函数表达式传递函数。

// Function invoked with parameter.
// TEST FAILS. DO NOT USE.
assert.throws(iThrowError(badParam), Error, "Error thrown"); // WRONG!

// Function invoked with parameter; wrapped in anonymous function for test.
// TEST PASSES.
assert.throws(function () { iThrowError(badParam) }, Error, "Error thrown");

// Function invoked with parameter, passed as predicate of ES6 arrow function.
// TEST PASSES.
assert.throws(() => iThrowError(badParam), Error, "Error thrown");

而且,仅仅为了彻底,这里有一个更文字的版本:

// Explicit throw statement as parameter. (This isn't even valid JavaScript.)
// TEST SUITE WILL FAIL TO LOAD. DO NOT USE, EVER.
assert.throws(throw new Error("Error thrown"), Error, "Error thrown"); // VERY WRONG!

// Explicit throw statement wrapped in anonymous function.
// TEST PASSES.
assert.throws(function () { throw new Error("Error thrown") }, Error, "Error thrown");

// ES6 function. (You still need the brackets around the throw statement.)
// TEST PASSES.
assert.throws(() => { throw new Error("Error thrown") }, Error, "Error thrown");

答案 2 :(得分:19)

我看到您能够解决您的问题但无法检查特定错误。要使用Chai的expect / should语法,您可以使用throw()的不同签名中的参数:

@param{ ErrorConstructor } constructor
@param{ String | RegExp } expectederror message
@param{ String } message _optional_

在您的示例中,您应该能够使用以下任一项:

expect(iThrowError).to.throw(/Error thrown/);
expect(iThrowError).to.throw(Error, /Error thrown/);
expect(iThrowError).to.throw(new Error('Error thrown'));

(再次,从chai的文档中),您可以使用以下方法过滤其他错误消息:

expect(iThrowError).to.throw(Error).and.not.throw(/Another Error thrown/);

希望这有帮助!