简体   繁体   中英

JavaScript, mocha test for random numbers

I use the following code which return array of random numbers my question is how should I unit test it with mocha and chai since the issue here that is provide in every run random numbers...

var randomArray = function(start, end) {
  var range = [];
  var resetRange = function() {
    for (let i = start; i < end; i++) {
      range.push(i);
    }
    shuffle(range);
  };

  return function(n) {
    if (range.length === 0) {
      resetRange();
    }
    return range.splice(0, n);
  };
};


var arr = randomArray(10,20);

arr(10) will provide for example

[15, 16, 14, 17, 11, 19, 18, 10, 12, 13]

arr(3) will provide for example

[18, 15, 10]
  1. You can obviously verify number of elements.
  2. You can run it twice (or various times) and verify that elements are varying (in chai assert.notDeepEqual ).
  3. If each element is from certain range, you can verify that also. Just loop through the generated array and verify that each element is greater than start and less than end .
  4. You can test Point #3 with different start and end values.
  5. Test edge cases start and end , eg for start > end , start === end , start < 0 , ....

It depends on level of confidence you want to achieve and time you can spent on that testing.

Examples of some points I mentioned (in ES5 syntax as question is using it):

var assert = require('chai').assert;

var testLength = function(length) {
    // WHEN
    var actualLength = randomArray(10, 20)(length).length;

    // THEN
    assert.equal(actualLength, length);
};

var testElementsRange = function(start, end) {
    // WHEN
    var actualArray = randomArray(10, 20)(10);

    // THEN
    for (var index = 0; index < actualArray.length; ++index) {
        assert.isAtLeast(actualArray[index], start);
        assert.isAtMost(actualArray[index], end);
    }
}

describe('randomArray', function() {
    describe('generates array', function() {
        it('with length 3', function() {
            testLength(3);
        });

        it('with length 10', function() {
            testLength(10);
        });

        it('with random elements', function () {
            // WHEN
            var array1 = randomArray(10, 20)(10);
            var array2 = randomArray(10, 20)(10);

            // THEN
            assert.notDeepEqual(array1, array2);
        });

        it('with elements within 10-20 range', function () {
            testElementsRange(10, 20);
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM