繁体   English   中英

使用 mocha chai 测试 node.js 中引发的错误

[英]test for error thrown in node.js using mocha chai

我是 node.js 的新手,我在为 function 设置简单的单元测试时遇到问题,我预计会引发错误。 我的 function 很简单:

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

我想测试我的 function 在没有参数传递给它时是否抛出错误。 在我的测试文件夹中,我有一个测试文件

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

我真的看不出我所期望的和我得到的有什么不同——那么为什么我在这里没有通过测试呢? 我希望它是带引号的东西?

谢谢/基拉

您正在将TypeError的新实例传递给expect() function,这意味着它将期望您的which_min() function 抛出该确切的错误实例(但它不会这样做,它会抛出相同错误类型的另一个实例具有相同的错误消息)。

尝试只传递错误字符串,所以:

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

编辑:

正如@Sree.Bh 所提到的,您还可以将预期的错误类型和预期的错误消息传递给throw()断言,如下所示:

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, "Cannot read property 'length' of undefined")
    })
  })
})

同意@krisloekkegaard 解释为什么expect(function(){utils.which_min();}).to.throw(new TypeError("Cannot read property 'length' of undefined"))失败:

要检查“错误类型”和“消息”,请使用

expect(function () { utils.which_min(); })
.to.throw(TypeError, "Cannot read property 'length' of undefined");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM