我正在尝试为使用Nodeunit在Node.js中编写的模块创建一个测试套件.该模块是一个基本的音乐播放列表,允许添加和删除曲目到播放列表.
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(); }
你可以看到有地方根据不正确的数据传入错误.
所以这里是我的测试套件.
var pl = require('./playlist'); exports.testPlaylistInit = function(test){ var playlist = pl.playlist(); test.equal(typeof playlist,'object'); test.done(); } exports.testAddingTracks = function(test){ var playlist = pl.playlist(); test.throws(playlist.addtrack(),Error,'Should fail for blank track'); var track = { title: "Golly Sandra",artist: "Eisley",album: "Room Noises" }; tracks = playlist.addtrack(track); test.equals(tracks[0],track); test.equals(tracks[0].id,1) test.done(); } exports.testRemoveingTracks = function(test){ var playlist = pl.playlist(); test.throws(playlist.removetrack('Imma error'),'Show fail for non-numeric track id'); var track = { title: "Golly Sandra",album: "Room Noises" }; playlist.addtrack(track); track = { title: ".44 Calliber Love Letter",artist: "Alexisonfire",album: "Alexisonfire" } playlist.addtrack(track); test.equals(playlist.removetrack(1)[0],track); test.throws(playlist.removetrack(10),'Should fail for non-existant track'); test.done(); }
在编写测试套件时,我使用test.throws作为假设,基本上只是将代码块包装在一个try-catch语句中,并检查catch对错误块.显然我错了,因为当我使用Nodeunit运行测试时,Node会显示模块抛出的错误消息,而不是测试套件捕获错误.我使用test.throw的情况不正确吗?
解决方法
你对test.throws的使用是不正确的.如果你看看你有什么:
test.throws( playlist.removetrack('Imma error'),'Show fail for non-numeric track id' );
您正在执行playlist.removetrack(‘Imma error’),然后将其结果传递给throws,因此如果有异常,则会在throws被执行之前发生.
你应该做一些更像这样的事情:
test.throws( function() { playlist.removetrack('Imma error'); },'Show fail for non-numeric track id' );
你必须传递一个功能,当执行时,会尝试删除轨道.这样,您的播放列表逻辑实际上由throws函数执行,因此可以自动包装在try / catch块中.