I have set up my unit tests in AngularJS with a Karma test runner and a Jasmine test framework. My code coverage report nicely shows me which lines and conditionals have been covered in my test. It is with this coverage report that I realised an if
conditional in my code (see below) is not being tested. Do I need to create a mock for the angular.forEach()
call? And if so, how exactly to do this? With ngMock?
To make my question a bit more clear, I would like to provide you with an example using an if
conditional in an angular.forEach()
call.
Say for example I have the following service:
angular.module('myApp').service('myService', function () {
function myFunction(myFunctionParameters) {
// ... Some irrelevant code...
var x = [];
angular.forEach(xObjs, function(o) {
if (some condition) { // <--- Code coverage says this is not tested!!
// do something...
}
});
// ... Some more irrelevant code
return // Something //
}
return {
myFunction: myFunction
};
});
A test for "myService" could be something like this:
describe("myService", function() {
// Some variables
// Declare the mocking variable
// Invoke the module
beforeEach(module('myApp'));
beforeEach(function(){
// Define the mock variable
mockVariable = <define mock variable here>
module(function($provide) {
$provide.value('serviceToMockName', mockVariable);
});
// Inject the services
inject(function(_myService_) {
myService = _myService_;
});
// Spy on the mock
// Call myFunction function in myService
result = myService.myFunction(functionParameters);
});
// Write some tests for the myFunction call in myService
describe("myFunction", function() {
it("should test the if condition...", function() {
// How to make sure I did the condition check in the if statement!!
});
});
});
Aucun commentaire:
Enregistrer un commentaire