我是Node.js的新手,我在为一个函数设置简单的单元测试时遇到了一些问题,我希望这个函数会抛出一个错误。 我的功能很简单:
const which_min = function(array) {
var lowest = 0;
for (var i = 1; i < array.length; i++) {
if (array[i] < array[lowest]) lowest = i;
}
return lowest;
}
我想测试当没有参数传递给我的函数时,它是否会抛出错误。 在我的测试文件夹中,我有一个测试文件
var assert = require('chai').assert;
var expect = require('chai').expect;
describe('#which_min()', function() {
context('with incorrect arguments', function() {
it('errorTest', function() {
expect(function(){utils.which_min();}).to.throw(new TypeError("Cannot read property 'length' of undefined"))
})
})
})
但我发现了一个非常奇怪的错误:
AssertionError: expected [Function] to throw 'TypeError: Cannot read property \'length\' of undefined' but 'TypeError: Cannot read property \'length\' of undefined' was thrown
+ expected - actual
我真的看不出我所期望的和我所得到的有什么不同--那么为什么我没有通过这里的测试呢? 我希望它是带引号的?
谢谢/Kira
您正在将TypeError的一个新实例传递给.expect()
函数,这意味着它将期望您的which_min()
函数抛出那个确切的错误实例(但它不会这样做,它将抛出另一个具有相同错误类型的实例,并带有相同的错误消息)。
尝试只传递错误字符串,所以:
var assert = require('chai').assert;
var expect = require('chai').expect;
describe('#which_min()', function() {
context('with incorrect arguments', function() {
it('errorTest', function() {
expect(function(){utils.which_min();}).to.throw("Cannot read property 'length' of undefined")
})
})
})
在这种情况下,Chai将期望抛出具有相同错误消息的任何错误类型。
您也可以选择断言错误为TypeError
,如下所示:
var assert = require('chai').assert;
var expect = require('chai').expect;
describe('#which_min()', function() {
context('with incorrect arguments', function() {
it('errorTest', function() {
expect(function(){utils.which_min();}).to.throw(TypeError)
})
})
})
但您并没有断言错误消息就是您所期望的。
有关更多信息,请参阅Chai官方文档:https://www.chaijs.com/api/bdd/#method_throw
同意@Krisloekkegaard解释expect(function(){utils.Which_min();}).to.throw(new TypeError(“无法读取未定义的属性'length'”))
失败的原因:
要检查“错误类型”和“消息”,请使用:
expect(function () { utils.which_min(); })
.to.throw(TypeError, "Cannot read property 'length' of undefined");