I'm trying to unit test an AngularJS service that is dependent on another service, using QUnit as my testing framework. The first test I'm writing is one to verify that my service calls another service under specific circumstances.
Below is a runnable example. I'm mainly looking to get feedback on the contents of the second main closure (which represents a QUnit module). Things I'm particularly interested in:
- Conventions around unit testing AngularJS services with QUnit (e.g. I'm unsure when it's common to prefix variables with a
$
); - I'm following this advice (which was for Jasmine though) on mocking a dependent service, but am unsure if I can improve that approach or even need a different one (heck, perhaps I even need / should use a mocking framework?);
- Whether I'm using the
injector
features of Angular correctly.
Here's a runnable snippet with promised code:
(function() {
var app = angular.module('demoApp', []);
app.factory('myService', ['anotherService', function(anotherService) {
return {
getTheTruth: function() { return anotherService.someFunction(); }
};
}]);
})();
(function() {
// Looking to get feedback on this closure...
'use strict';
var $injector, anotherService;
QUnit.module('myServiceTests', {
beforeEach: function() {
anotherService = {};
angular.module('demoApp').factory('anotherService', function() {
return anotherService;
});
$injector = angular.injector(['ng', 'demoApp']);
}
});
QUnit.test('Calling getTheTruth relays to anotherService', function(assert) {
var service = $injector.get('myService');
anotherService.someFunction = function() {
assert.ok(true);
};
assert.expect(1);
service.getTheTruth();
});
// More tests here
})();
<link href="https://cdnjs.cloudflare.com/ajax/libs/qunit/1.16.0/qunit.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/qunit/1.16.0/qunit.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular.js"></script>
<div id="qunit"></div>
angular-mocks
. \$\endgroup\$