Javascript Nodeunit test.com';我似乎没有抓住错误

Javascript Nodeunit test.com';我似乎没有抓住错误,javascript,unit-testing,node.js,nodeunit,Javascript,Unit Testing,Node.js,Nodeunit,我正在尝试为我正在Node.js中使用Nodeunit编写的模块创建一个测试套件。该模块是一个基本音乐播放列表,允许在播放列表中添加和删除曲目 var playlist = function(){ this.__playlist = []; this.__count = 0; }; playlist.prototype = { addtrack:function(track){ if(typeof track !== "object") throw ne

我正在尝试为我正在Node.js中使用Nodeunit编写的模块创建一个测试套件。该模块是一个基本音乐播放列表,允许在播放列表中添加和删除曲目

var playlist = function(){
    this.__playlist = [];
    this.__count = 0;
};

playlist.prototype = {
    addtrack:function(track){
        if(typeof track !== "object") throw new Error("Track needs to be an oject");
        this.__count++;
        track.id = this.__count;
        this.__playlist.push(track);
        return this.__playlist;
    },
    removetrack:function(trackid){
        if(typeof trackid !== "number") throw new Error("Pass in a numeric track id");
        var trackFound = false;
        for(var i=0;i<this.__playlist.length;i++){
            var t = this.__playlist[i];
            if(t.id == trackid){
                trackFound = true;
                this.__playlist.splice(i,1);
            }
        }
        if(!trackFound) throw new Error("Track not found in the playlist");
        return this.__playlist
    }
}

exports.playlist = function(){
    return new playlist();
}

在编写测试套件时,我使用test.throws作为假设,基本上只是将代码块包装在try-catch语句中,并根据错误块检查捕获。显然我错了,因为当我使用Nodeunit运行测试时,Node显示模块抛出的错误消息,而不是测试套件捕获错误。我是否错误地使用了test.throw案例?

您对test.throw的使用不太正确。如果你看看你所拥有的:

test.throws(
  playlist.removetrack('Imma error'),
  Error,
  'Show fail for non-numeric track id'
);
您正在执行playlist.removetrack('Imma error'),然后将结果传递给throws,因此如果出现异常,它将在执行throws之前发生

你应该做更多类似的事情:

test.throws(
  function() {
    playlist.removetrack('Imma error');
  }, 
  Error,
  'Show fail for non-numeric track id'
);

您必须传入一个函数,该函数在执行时将尝试删除该轨迹。这样,播放列表逻辑实际上由throws函数执行,因此可以自动包装在try/catch块中。

perfect,golden。。。。也许类似的示例也应该添加到nodeunit的自述文件中;)
test.throws(
  function() {
    playlist.removetrack('Imma error');
  }, 
  Error,
  'Show fail for non-numeric track id'
);