Unit testing promises in AngularJS with arguments
by Krzysztof Safjanowski
HTML
<script src="http://jasmine.github.io/1.3/lib/jasmine.js"></script>
<script src="http://jasmine.github.io/1.3/lib/jasmine-html.js"></script>
<link rel="stylesheet" href="http://jasmine.github.io/1.3/lib/jasmine.css">
<script src="http://code.angularjs.org/1.2.9/angular.js"></script>
<script src="http://code.angularjs.org/1.2.9/angular-mocks.js"></script>
<script src="https://code.angularjs.org/1.2.9/angular-resource.js"></script>
JavaScript
//--- CODE --------------------------
(function (angular) {
angular.module("App", []).service("ServiceA", function ($http, ServiceB) {
this.detail = null;
this.method = function (id) {
return ServiceB.getId(id).then(function (response) {
this.detail = response.data;
});
};
});
})(angular);
// ---SPECS-------------------------
describe('ServiceA', function () {
var serviceA, serviceBMock, $q;
beforeEach(function () {
module('App');
});
beforeEach(function () {
var _serviceBMock = {
getId: function() {}
};
angular.module('App')
.value('ServiceB', _serviceBMock);
});
beforeEach(inject(function (_ServiceA_, _ServiceB_, _$q_) {
$q = _$q_;
serviceA = _ServiceA_;
serviceBMock = _ServiceB_;
}));
describe('.method()', function () {
it('returns ServiceB.getId() argument', function () {
var mockId = Math.floor(Math.random() * 10);
spyOn(serviceBMock, 'getId').andReturn($q.all());
serviceA.method(mockId);
expect(serviceBMock.getId).toHaveBeenCalledWith(mockId);
});
});
});
// --- Runner -------------------------
(function () {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function (spec) {
return htmlReporter.specFilter(spec);
};
var currentWindowOnload = window.onload;
window.onload = function () {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();