简体   繁体   中英

Javascript NaN preventing from running angular unit tests

I am attempting to test a directive but when I mock out the directive a line in the middle of the directive runs an error. Which prevents my tests from running

$scope.getIterations = function (its) {
        return new Array(its);
    };

Returns

 RangeError: Invalid array length

Which makes sense as the argument its returns NaN .

I figured that I could call var its = [1,2,3]; $scope.getIterations(its)

Inside of a beforeEach but that did not make any difference as the error code returns the same thing.

Maybe I am misunderstanding this code, but I am not sure how to get around this for the unit tests.

It seems it has to do with new . If your trying to instantiate a new array then try instantiating your array with Array Literal instead of the constructor:

$scope.getIterations = function (its) {
        return [its];
};

but as others have pointed out, it's unclear exactly what you want to return, so if its is an array. You can just return its; .

The exception is pretty self explanatory: you're passing an Array when new Array() expects variadic arguments as items to insert or a length to pad :

$scope.getIterations = function(its) {
    return new Array(its.length);
};

It's not exactly clear what you're trying to do here... Seems like you'd just want to return the argument as-is:

$scope.getIterations = function(its) {
    return its;
};

Array construction takes comma separated values which will become the elements of the array, with an exception that if it has only one numeric id, it will generated array of that much length with undefined as its elements.

new Array("a") // ["a"]
new Array("a","b")//["a","b"]
new Array(3,2) //[3,2]
new Array(3) //[undefined x 3]

in your case if the value of its is an array, you can return the variable itself.

return its;

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