سؤال

I have a short function which gets an array and shuffles the values "around".

array_name.sort(function() { return 0.5 - Math.random() });

How can I test that I get a different array then I had before?

Of course I can mock the array, and then test if

array_name[2] != array_after[2];

But, as its random, it could happen that sometimes this position is equal and sometimes not.

What is a good approach to this?


So, its about testing the randomness

I have an approach, and of course my problem:

it('different option order when randomization is true', function() {
  var array = // getting from json.file here
  var array_after = question.shuffle(array);

  expect(array[4].text.localeCompare(array_after[1].text)).toBe(0);

});

Of course, i cannot say now that this is always different. Because i run my tests several times, and sometimes they are the same, and sometimes not...

هل كانت مفيدة؟

المحلول 2

If you need to compare if the before / after arrays are indeed different, do something like this:

function arraysAreEqual(before, after){
    if(before.length !== after.length){
        return false;
    }
    for(var i = 0; i < before.length; i++){
        if(before[i] !== after[i]){
            return false;
        }
    }
    return true;
}

Depending on the contents of the arrays, you may need to modify the equality check in the for loop to account for nested arrays / objects.

Assuming:

var myArray = [
    {text: 'foo', value: 1},
    {text: 'bar', value: 2}
]

You can use this, for example:

if(before[i].text !== after[i].text ||
   before[i].value !== after[i].value){
    return false;
}

With this function, you should be able to use:

expect(arraysAreEqual(array, array_after)).toBe(false);

However, the test case will fail in the (improbable, but possible) case the randomizer returns the same array as the input.

نصائح أخرى

What you're after is a seeded random number generator. In your tests you can control the seed and verify that different seeds consistently generates different numbers.

See http://indiegamr.com/generate-repeatable-random-numbers-in-js/ for more information.

Related questions:

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top