Tag Archives: angular unit test

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 = 'http://www.omdbapi.com/?v=1&';

        function httpPromise (url) {
			var deferred = $q.defer();
				.success(function(data) {
				.error(function(error) {
			return deferred.promise;

        service.search = 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 = 'http://www.omdbapi.com/?v=1&s=star%20wars';
        moviesApi.search('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!

Introduction Set up TTD for Angular App – to be continue

Step 1 : go to Jasmine release page https://github.com/jasmine/jasmine/releases download the standalone zip file.

Step2: create a project folder in your computer where you like to put it, unzip the jasmine standalone zip file inside your project folder, then we could delete the sample files inside src and spec folder since we won’t using it, but keep the folder, so we could still using it.

Step3:  run npm init (make sure nodejs has been install in your computer) will create package.json file

Step4: install karma as test runner

npm install karma --save-dev

Step5: install -g karma-cli

Step6: npm install karma-jasmine karma-chrome-launcher –save-dev

Step7:karma init (for add the config file for karma)


Step 8: normal running test in phantom is fast so also need install packages:

“karma-phantomjs-launcher”: “^0.2.1”,
“phantomjs”: “^1.9.18”

Now your package.json file will look like this

  "name": "sample",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
     "test": "karma start karma.conf.js"
  "keywords": [
  "author": "sandy zhang",
  "license": "ISC",
  "devDependencies": {
    "jasmine-core": "^2.3.4",
    "karma": "^0.13.9",
    "karma-chrome-launcher": "^0.2.0",
    "karma-jasmine": "^0.3.6",
    "karma-phantomjs-launcher": "^0.2.1",
    "phantomjs": "^1.9.18"

Step9: Add angularjs and angular-mock.js into the lib folder, and included it into the karma config file

// Karma configuration
// Generated on Sat Nov 12 2016 22:15:24 GMT+1100 (AUS Eastern Daylight Time)

module.exports = function(config) {

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [

    // list of files to exclude
    exclude: [

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity

Now I create a calculater.js file inside src folder with one function

function add(x,y){
return x+y;

And create your first calculater.spec.js inside spec folder

it(‘should add two number’,function(){

then run npm test, then your will get your result.