Angular 1.x - Unit Testing a function that returns Promise

I wrote this post few months back which show how we can mock a function that returns Promise. In this post, we will see how to test a function that returns Promise.

We will use the following simple controller as our SUT

var app = angular.module("app");

app.controller("studentController", function($q, studentDataService){
    var vm = this;    
    vm.students = undefined;
    function activate (){
        vm.students = getAllStudents();
    function getAllStudents(){
        return studentDataService

This simple controller has getAllStudents() which returns a promise. The activate method calls getAllStudents() and assigns the returned promise to vm.students. In angular, you can directly bind promise, so, this is perfectly valid.

When it comes to testing, we would like to test what data this promise returns when it is resolved.

And, this is how we do it,

it("should get students on activation", function(done){
    // Fixture Setup
    // Exercise Systcode
    var sut = $controller("studentController");
    // Verify Outcome
    // Fixture Teardown

In this test, we are considering sut.students as promise and the assert is written inside the then() method. Because assert is written inside the then()method, we have access to the data the promise returns when resolved. This means, we can directly test the data returned by the promise. In this example, I have simply verified whether the data is defined or not, but, it can be anything.

This test method also uses jasmine’s asynchronous spec and done()callback is called inside the then() method after the assert statcodeent. This helps to complete the test as soon as our assert ran and it also time out the test if the then() is not defined or not called for some reason.

Isn’t this simple and effective?

comments powered by Disqus