Skip to content

Instantly share code, notes, and snippets.

@vtanathip
Last active December 21, 2015 15:19
Show Gist options
  • Save vtanathip/6326069 to your computer and use it in GitHub Desktop.
Save vtanathip/6326069 to your computer and use it in GitHub Desktop.
Example AngularJS Services Unit Testing ( Mock all $http dependencies )
angular.module('angularApp')
.factory('loadConfig', function($http) {
return {
getPageInfo : function(page) {
return $http.get('configurations/en/' + page + '.json').then(
function(response) {
return response.data;
});
}
};
})
'use strict';
describe('Services: loadConfig ', function () {
var scope, loadConfig, httpBackend;
beforeEach(function () {
//load the module.
module('angularApp');
//inject your service for testing.
inject(function ($httpBackend, $injector, $rootScope) {
loadConfig = $injector.get('loadConfig');
httpBackend = $httpBackend;
scope = $rootScope.$new();
});
});
//check our expectations were missed in tests.
afterEach(function () {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
it('should return msg and verify expexctations', function () {
var returnData = { excited: "so much" };
httpBackend.whenGET('configurations/en/main.json').respond(returnData);
//promise object
var returnedPromise = loadConfig.getPageInfo('main');
//we handle with promise object
returnedPromise.then(function(data){
expect(data.excited).toBe("so much");
});
//flush for http request
httpBackend.flush();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment