在磁带节点中断言

所以我试图testing一个函数,它是一个客户端函数(未完成),这就是为什么它被embedded在testing本身(直到我能找出一个更好的解决scheme)。

我遇到的问题是当我testing,看看是否该函数抛出一个TypeError。

我明白这个问题是因为它是testing返回值而不是函数本身,我不确定如何解决这个问题。

任何和所有的帮助表示赞赏!

胶带


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执行非操作,然后testing它是否是instanceof Array一个instanceof Array 。 所以你真正想要的是:

 if(!(tickets instanceof Array)){ throw new TypeError(); } 

接下来的问题是,就像你说的那样,你正在得到GenerateRandomNumber的返回值,如果抛出一个错误,那么返回值不是TypeError。 如果你想保持你的try / catch并在GenerateRandomNumber返回false,那么你不需要throwstesting,而是像下面这样:

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,因为按预期方式传递函数时,磁带的匹配错误是相当奇怪的(请参阅此问题 )。 我正在寻找这样做的select仍然,但希望这可以帮助你现在。