Last active
December 21, 2015 15:19
-
-
Save vtanathip/6326069 to your computer and use it in GitHub Desktop.
Example AngularJS Services Unit Testing ( Mock all $http dependencies )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module('angularApp') | |
.factory('loadConfig', function($http) { | |
return { | |
getPageInfo : function(page) { | |
return $http.get('configurations/en/' + page + '.json').then( | |
function(response) { | |
return response.data; | |
}); | |
} | |
}; | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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