TDD Test AngularJs Service $Http

In my last post I have hardcode the data into the service to let my test pass, now in this post I will change that service to by inject the $http service into my module and let it return httpPromise.

Here is my new movieApi.js file

   "use strict";
  var app =  angular.module('moviesApi',[]);

    app.factory('moviesApi',function($http, $q){
        var service = {};
        var baseUrl = '';

        function httpPromise (url) {
			var deferred = $q.defer();
				.success(function(data) {
				.error(function(error) {
			return deferred.promise;
		} = function(query) {
			return httpPromise(baseUrl + 's=' + 
   return service;

Then my unit test fail, that is because now my service return a promise and it has not resolve yet, but my test expect data, for how to solve this issue, angularjs has provide $httpBackend for Fake HTTP backend implementation for unit testing application that use the $http service.

Here is the new test code:

         //angular.mock is under the globe variable, so I have remove it 
         //the beforeEach is jasmine provide if you have multiple test need 
         //the same  set up, it will automatic set for each test, will reduce copy code
         //for name convenience  I also changed the service's name 
         //to match the module name
        //then in the dependence inject angularjs allow your put the underscore 
        //for your inject service,it will pick it up
	beforeEach(inject(function(_moviesApi_,_$httpBackend_) {
		moviesApi = _moviesApi_;
                $httpBackend = _$httpBackend_;
    it('should return search movies data',function(){
        var response;
        var expectedUrl = '';
       'star wars')
                        response = data;

        //the fake $httpBackend has function flush will resolve the data for you to       //test



Tips: as frondend developer also could using this Fake data create a service response, so you do not need waiting for the backend service finished to do your job.


Now the test will pass.

Have fun!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s