简体   繁体   English

JavaScript,随机数的摩卡测试

[英]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... 我使用下面的代码返回随机数组我的问题是我应该如何用mocha和chai进行单元测试,因为这里的问题是每次运行随机数提供的...

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 arr(10)将提供

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

arr(3) will provide for example arr(3)将提供

[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 ). 您可以运行它两次(或不同次)并验证元素是否变化(在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 . 只需遍历生成的数组并验证每个元素是否大于start而不是end
  4. You can test Point #3 with different start and end values. 您可以测试点#3具有不同的startend的值。
  5. Test edge cases start and end , eg for start > end , start === end , start < 0 , .... 测试边缘情况startend ,例如start > endstart === endstart < 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): 我提到的一些要点的例子(在ES5语法中,问题就是使用它):

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);
        });
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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