所以我正在尝试测试一个函数,它是一个客户端函数(未完成),这就是为什么它被嵌入到测试本身中(直到我能找到更好的解决方案)。
我遇到的问题是,当我测试函数是否抛出TypeError时。
我知道问题是因为它测试的是返回值,而不是函数本身,我不确定如何解决这个问题。
感谢所有人的帮助!
磁带
test.js
var test = require('tape');
test('GenerateRandomNumber Tests', function(assert){
/**
* Generates a random number between the min/max
* @param {int} the min value
* @param {int} the max value
* @param {array} list of values already stored
* @return {mixed} int if success, false if exception thrown
**/
var GenerateRandomNumber = function( min, max, tickets ){
try{
if(!tickets instanceof Array){
throw new TypeError();
}
min = (min) || 0;
max = (max) || 200;
var n = 0;
n = ~~(Math.random() * (max - min) + min);
if(tickets.indexOf(n) === 1){
GenerateRandomNumber(min, max);
}
return n;
}catch(e){ return false; }
};
assert.plan(4);
var t1 = GenerateRandomNumber(0, 300, null);
assert.equal(typeof t1, "boolean", "Should return a boolean - false");
var t2 = GenerateRandomNumber(0, 300, [0,1,2,3,4]);
assert.equal(typeof t2, "number", "Should return a typeof number");
// HELP
assert.throws(GenerateRandomNumber(0, 300, null), TypeError, "Should throw typeError");
var t4 = GenerateRandomNumber(null, null, [0,1,2,3,4]);
assert.equal(typeof t4, "number", "Should return a typeof number");
});
第一个问题是!tickets instanceof Array
不是您想要的逻辑。它首先对tickets
执行not操作,然后测试它是否是instanceof Array
。所以你真正想要的是:
if(!(tickets instanceof Array)){
throw new TypeError();
}
下一个问题是,正如您所说,您将获得GenerateRandomNumber
的返回值,如果抛出错误,则返回值为false
,而不是TypeError。如果你想在GenerateRandomNumber
中保持try/catch并返回false,那么你不需要throws
测试,而是需要类似于的测试
assert.equal(GenerateRandomNumber(0, 300, null), false, "Should catch the TypeError and return false)
如果你想使用assert.throws
,那么你需要从GenerateRandomNumber
中删除try/catch,而是这样做:
var test = require('tape');
test('GenerateRandomNumber Tests', function(assert){
/**
* Generates a random number between the min/max
* @param {int} the min value
* @param {int} the max value
* @param {array} list of values already stored
* @return {mixed} int if success, false if exception thrown
**/
var GenerateRandomNumber = function( min, max, tickets ){
if(!(tickets instanceof Array)){
throw new TypeError('error');
}
min = (min) || 0;
max = (max) || 200;
var n = 0;
n = ~~(Math.random() * (max - min) + min);
if(tickets.indexOf(n) === 1){
GenerateRandomNumber(min, max);
}
return n;
};
assert.plan(3);
var t2 = GenerateRandomNumber(0, 300, [0,1,2,3,4]);
assert.equal(typeof t2, "number", "Should return a typeof number");
// You must wrap GenerateRandomNumber from within another function
//so that the error being thrown doesn't cause the program to exit
assert.throws(() => GenerateRandomNumber(0, 300, null), /error/, "Should throw typeError");
var t4 = GenerateRandomNumber(null, null, [0,1,2,3,4]);
assert.equal(typeof t4, "number", "Should return a typeof number");
});
我使用了传递RegExp的选项,因为在按预期传递函数时,磁带的错误匹配非常奇怪(请参阅此问题)。我仍然在考虑这样做的选择,但希望这对你现在有所帮助。