Cpo Design

Angular unit testing using $httpBackend

Pavel Svarc Monday, January 25, 2016 6:27 AM

Writing unit tests for any part of software is being part of common practise for all sw houses that take software seriously.

I have learned all about writing tests in angular.js and wrote loads of notes while writing applications. Moving a job and not taking my notes has left me with only half of the knowledge. So after spending couple hours refreshing my knowledge I have decided to share my experience.


I have created a example to show how to create a test for data access. I hope the code below is explanatory by itself.

/// <reference path="/scripts/jquery-1.10.2.js" />
/// <reference path="/scripts/angular/angular.js" />
/// <reference path="/scripts/angular/angular-resource.js" />
/// <reference path="/scripts/angular/angular-filter.js" />
/// <reference path="/scripts/angular/angular-mocks.js" />

/// <reference path="/scripts/services/dataservice.js" />
/// <reference path="/scripts/controllers/example.js" />
/// <reference path="/scripts/app.js" />

describe('Example controller backend calls tests', function () {
    var controller;
    var httpBackend;
	var $controller;
	var $filter;    
	var $scope ;    
    var $http ;
    // Method run before each test is run
    beforeEach(function () {

        app.controller('ExampleController', ExampleController);
        // get all times you need for application 
        inject(function ($rootScope, $controller, $filter, $http, $httpBackend) {
            $controller = $controller;
            $filter     = $filter;
            $scope      = $rootScope.$new();
            $http       = $http;
            httpBackend     = $httpBackend;

            controller = $controller('ExampleController',
                $scope: $scope,
                $http: $http,
                $filter: $filter
	   // respond definition generic
            httpBackend.when("POST", '/api/pricelist/1/update').respond([{}, {}, {}]);            

    describe('Data access for price list', function () {
        it('should post data to service', function() {

            var model = {}
            model.Name = 'test';
            model.Price = 1;

            httpBackend.expectPOST('/api/pricelist/1/update', angular.toJson(model)).respond(200);
			      controller.$scope.model.Name = 'test';
            controller.$scope.model.Price = 1;


Related posts

Currenlty there are no related articles.