我有一个函数(detectNetwork),它检查信用卡号码,如果它与公认的供应商匹配,则识别该卡的供应商。我有另一个函数(detectNetworkTest),使用Mocha可以调用它来测试detectNetwork并验证它是否正常工作。
我正在对中国银联进行验证,在调用detectNetworkTest时收到以下错误:
TypeError: Cannot read property 'should' of undefined在上下文。(detectNetwork.test.js: 241:39)
指的是detectNetworkTest中的这一行:
detectNetwork(cardNumberToCheck).should.equal('China UnionPay');
当运行这个函数时,我可以通过登录到控制台确认cardNumberToCheck是我需要利用的正确值,所以我有点卡在试图确定为什么它被读取为未定义。
detectNetwork
var detectNetwork = function(cardNumber) {
// Note: `cardNumber` will always be a string
var re = {
"Diner's Club": /^3[8-9][0-9]{12}$/,
"American Express": /^3[4,7][0-9]{13}$/,
"Visa": /^4([0-9]{12}|[0-9]{15}|[0-9]{18})$/,
"MasterCard": /^5[1-5]([0-9]{14})$/,
"Discover": /^6(011|5[0-9]{2}|4[4-9]{1}[0-9]{1})[0-9]{12,15}$/,
"Maestro": /^(5018|5020|5038|6304)[0-9]{8,15}$/
}
for(var card in re) {
if(re[card].test(cardNumber)) {
return card;
}
}
}
detectNetworkTest
describe('should support China UnionPay', function() {
var should = chai.should();
var prefixes = [];
var randomNumber = Math.random().toString(7).substr(2, 17);
var randomCardNumbers = [];
for(i=624; i<627; i++) {
prefixes.push(i);
}
for(j=622126; j<622926; j++) {
prefixes.push(j);
}
for(k=6282; k<6288; k++) {
prefixes.push(k);
}
prefixes.forEach(value => {
for(i=14; i<18; i++) {
var randomCardNumber = (value + "x" + randomNumber).substring(0,i);
randomCardNumbers.push(randomCardNumber);
};
});
randomCardNumbers.forEach(value => {
var prefix = value.split("x")[0];
var cardNumberToCheck = value.replace("x","");
it('has a prefix of ' + prefix + ' and a length of ' + cardNumberToCheck.length, function() {
detectNetwork(cardNumberToCheck).should.equal('China UnionPay');
});
});
});
detectNetwork(cardNumberToCheck)
的计算结果为undefined
这是因为如果re[card].test(cardNumber)
绝对不匹配,则没有return