Search code examples
javascriptmocha.jschaiassert

Testing 40+ combinations on Mocha/Chai for JS


Learning Mocha + Chai for JS right now and I'm a bit stumped on how to test for this bit of code:

for (var j = 12; j <= 19; j++) {
    if (cardNumber.length === j) {
        if (cardNumber.slice(0, 4) === '5018') {
            return 'Maestro';
        } else if (cardNumber.slice(0, 4) === '5020') {
            return 'Maestro';
        } else if (cardNumber.slice(0, 4) === '5038') {
            return 'Maestro';
        } else if (cardNumber.slice(0, 4) === '6304') {
            return 'Maestro';
        }
    }
}

I'm testing to see if an input string which is a card number satisfies any of the conditions below with the first 4 elements being specified and the length of the card has to be between 12 & 19.

describe('Maestro', function() {
  // Write full test coverage for the Maestro card
  var should = chai.should();

  for (var length = 12; length <= 19; length++) {
    (function(length) {
      it ('has a prefix of 5018 and a length of ' + length, function() {
        detectNetwork('5018' + ???).should.equal('Maestro');
      });
    })(length)
  };
});

I do not want to write all the test cases for each of the 4 prefixes + every length between 12 - 19. Is there a way where I can add to my prefix string by increasing it by the number of elements which is equal to the length?

I've tried putting a for loop with an array of additional ints from 12-19 and adding it to the prefix in the test function but it still doesn't work


Solution

  • I think you are looking for something like this:

    describe('Maestro', function() {
      // Write full test coverage for the Maestro card
      var should = chai.should();
      var prefixes = ['5018', '5020', '5038', '6304'];
      for(var p=0; p<prefixes.length;p++) {
          for (var length = 12; length <= 19; length++) {
            (function(length, prefix) {
              it ('has a prefix of ' + prefix + ' and a length of ' + length, function() {
                var longString = 'abcdefghijklmnopqrstuvwxyz';
                var testString = prefix + longString.slice(0, length-prefix.length);
                detectNetwork(testString).should.equal('Maestro');
              });
            })(length, prefixes[p])
          };
      }
    });