In the task of testing an angular factory, here is the code that needs to be tested:
var myApp = angular.module('myApp', []);
myApp.factory('factoryTest',function(){
return [
{number: 1, name: 'one'},
{number: 2, name: 'two'},
{number: 3, name: 'three'}
];
});
Using Jasmine for testing, the following approach can be taken:
beforeEach(inject(function (_factoryTest_) {
factoryTest = _factoryTest_;
}));
it('checks if each item has a number', function(){
for(var i=0;i < factoryTest.length; i++){
expect(factoryTest[i].number).toEqual(jasmine.any(Number));
}
});
Although the above test works, it can be improved by providing more specific details in case of failure.
To enhance error readability, refactor the test into individual 'its' within a loop:
beforeEach(inject(function (_factoryTest_) {
factoryTest = _factoryTest_;
}));
for(var i=0;i < factoryTest.length; i++){
it('verifies ' + factoryTest[i].name + ' contains a number', function(){
expect(factoryTest[i].number).toEqual(jasmine.any(Number));
});
}
However, this approach encounters issues as the factoryTest is not injected properly in the describe context. How can we effectively inject the angular factory?
A demonstration using a fiddle can be found here: http://jsfiddle.net/rodhom/woq9fhg9/
The concept of iterating 'its' was initially discovered from: