gpt4 book ai didi

javascript - Nodeunit test.throws 似乎没有发现错误

转载 作者:IT老高 更新时间:2023-10-28 23:23:08 24 4
gpt4 key购买 nike

我正在尝试为我使用 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'), Error, 'Show fail for non-numeric track id');
var track = {
title: "Golly Sandra",
artist: "Eisley",
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), Error, 'Should fail for non-existant track');
test.done();
}

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

最佳答案

您对 test.throws 的使用不太正确。如果你看看你有什么:

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 block 中。

关于javascript - Nodeunit test.throws 似乎没有发现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7020489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com