AngularJS Tests With An HTTP Mock

 Let’s look at a controller that likes to communicate over the network.

(function (module) {
 
    var MoviesController = function ($scope, $http) {
 
        $http.get("/api/movies")
            .then(function (result) {
                $scope.movies = result.data;
            });
    };
 
    module.controller("MoviesController",
        ["$scope", "$http", MoviesController]);
 
}(angular.module("myApp")));

If you want a unit test to execute without network communication there are a couple options. You could refactor the controller to use a custom service to fetch movies instead of using $http directly. Then in a unit test it would be easy to provide a fake service that returns pre-canned responses.

Another option is to use angular-mocks. Angular mocks includes a programmable fake $httpBackend that replaces the real $httpBackend service. It is important to note that $httpBackend is not the same as the $http service. The $http service uses $httpBackend to send HTTP messages. In a unit test, we’ll use the real $http service, but a fake $httpBackend programmed to respond in a specific way.

Here is one approach:

describe("myApp", function () {
 
    beforeEach(module('myApp'));
 
    describe("MoviesController", function () {
 
        var scope, httpBackend;
        beforeEach(inject(function ($rootScope, $controller, $httpBackend, $http) {
            scope = $rootScope.$new();
            httpBackend = $httpBackend;
            httpBackend.when("GET", "/api/movies").respond([{}, {}, {}]);
            $controller('MoviesController', {
                $scope: scope,
                $http: $http
            });
        }));
 
        it("should have 3 movies", function () {
            httpBackend.flush();
            expect(scope.movies.length).toBe(3);
        });
    });
});

In the above test, $httpBackend is programmed (with the when method) to respond to a GET request with three objects (empty objects, since the controller in this example never uses the data, but only assigns the response to the model).

For the data to arrive in the model, the test needs to call the flush method. Flush will respond to all requests with the programmed responses. The flush method will also verify there are no outstanding expectations. Writing tests with expectations is a little bit different.

describe("myApp", function () {
 
    beforeEach(module('myApp'));
 
    describe("MoviesController", function () {
 
        var scope, httpBackend, http, controller;
        beforeEach(inject(function ($rootScope, $controller, $httpBackend, $http) {
            scope = $rootScope.$new();
            httpBackend = $httpBackend;
            http = $http;
            controller = $controller;
            httpBackend.when("GET", "/api/movies").respond([{}, {}, {}]);
        }));
       
        it('should GET movies', function () {
            httpBackend.expectGET('/api/movies');
            controller('MoviesController', {
                $scope: scope,
                $http: http
            });
            httpBackend.flush();
        });
    });
});

The expectation in the above code is registered with the expectGET method. When the test calls flushflush will fail the test if the controller did not make all of the expect calls. Of the two tests in this post, I prefer the first style. Testing with expectations is the same as interaction testing with mocks, which I’ve learned to shy away from because interaction testing tends to be brittle.

Simple Unit Tests With AngularJS

For those of you that have company sites that still use AngularJs 1.3 - 1.6, heres a short help on how to unit test your code.

One of the benefits of using AngularJS is the ability to unit test the JavaScript code in a complex application. Unit testing is incredibly easy for trivial cases when controllers and models are declared in global scope. However unit testing is slightly more challenging for objects defined inside of Angular modules because of the need to bootstrap modules, work with a dependency injector, and deal with the subtleties of nested functional code. 

Let’s try to test the following controller defined in a module:

(function (app) {
     
    var SimpleController = function ($scope) {
      
        $scope.x = 3;
        $scope.y = 4;
        $scope.doubleIt = function () {
            $scope.x *= 2;
            $scope.y *= 2;
        };
    };
     
    app.controller("SimpleController", 
             ["$scope", SimpleController]);
     
}(angular.module("myApp")));

We’ll be using AngularJS mocks and Jasmine in an HTML page, which requires the following scripts:

- jasmine.js

- jasmine-html.js

- angular.js

- angular-mocks.js

- simpleController.js (where the controller lives)

It’s important to include the Jasmine scripts before including angular-mocks, as angular-mocks will enable some additional features when Jasmine is present (notably the helper methods module and inject).

describe("myApp", function() {
 
    beforeEach(module('myApp'));
 
    describe("SimpleController", function() {
 
        var scope;
        beforeEach(inject(function($rootScope, $controller) {
            scope = $rootScope.$new();
            $controller("SimpleController", {
                $scope: scope
            });
        }));
 
        it("should double the numbers", function() {
            scope.doubleIt();
            expect(scope.x).toBe(6);
        });
    });
});

 

[C# 8] New features

Readonly Members

Added new readonly modifiers to be used in structs, lets you define more granular properties that do not modify state.

eg consider the following mutable struct:-

public struct Point
{
    public double X { get; set; }
    public double Y { get; set; }
    public double Distance => Math.Sqrt(X * X + Y * Y);

    public override string ToString() =>
        $"({X}, {Y}) is {Distance} from the origin";
}

We can decorate the ToString() method as readonly as it doesnt modify state.

public readonly override string ToString() =>
    $"({X}, {Y}) is {Distance} from the origin";

when built this would produce a compile time error like:-

warning CS8656: Call to non-readonly member 'Point.Distance.get' from a 'readonly' member results in an implicit copy of 'this'

and would require the following change to the property so that it doesnt change the state, it doesnt assume that get accessors do not modify state.

public readonly double Distance => Math.Sqrt(X * X + Y * Y);

 

Default Interface Methods

You are now able to add functionality to interfaces without breaking functionality to older versions of implemented interfaces.

interface IWriteLine  
{  
 public void WriteLine()  
 {  
 Console.WriteLine("Wow C# 8!");  
 }  
}  

This has to be used carefully as it will easily violate the Single Responsibility principles

 

Nullable reference type

Allow you to induce compiler warnings then using reference types for more defensive coding.

string? nullableString = null;  
Console.WriteLine(nullableString.Length); // WARNING: may be null! Take care!  

 

Async streams

Allow the use of Async to be now used over collections and can be iterated over.

await foreach (var x in enumerable)  
{  
  Console.WriteLine(x);  
}

Now its possible to the client consumer to be able to consume async streams in chunks as they are returned and are available.

Ranges

You can now access data sequences in 2 new ways and get various slices of data that you require.

Indices

Access to collections by taking from the beginning or the end.

Index i1 = 3; // number 3 from beginning  
Index i2 = ^4; // number 4 from end  
int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };  
Console.WriteLine($"{a[i1]}, {a[i2]}"); // "3, 6" 

Sub collection

Obtain a sub collection from the data

var slice = a[i1..i2]; // { 3, 4, 5 } 

Null-coalescing assignment

New feature that allows you to null-coalesce assign with the ??= operator so if the value on the right is assigned to the left only if the left hand is null.

List<int> numbers = null;
int? i = null;

numbers ??= new List<int>();
numbers.Add(i ??= 17);
numbers.Add(i ??= 20);

Console.WriteLine(string.Join(" ", numbers));  // output: 17 17
Console.WriteLine(i);  // output: 17

Default in deconstruction

Allows the following syntax (int i, string s) = default; and (i, s) = default

(int x, string y) = (default, default); // C# 7  
(int x, string y) = default;               // C# 8  

 

Using declarations

Enhance the using operator to be more inline such as 

// C# Old Style  
using (var repository = new Repository())    
{    
} // repository is disposed here!    
     
// vs.C# 8    
     
using var repository = new Repository();    
Console.WriteLine(repository.First());    
// repository is disposed here!