Jasmine JS, Angular JS – Testing of an Angular Service with Mocking

To mock an Angular dependency we must create a mock module with all our mock objects defined through the $provide.value() method. Every time our target will require a particular dependency this will be taken from the mocking module.

In this example we updated our Angular Service Test to use a mock version of the “hangmanConstants” dependency (the original version was just calling the module(“hangmanApp.constants”) method to resolve the real dependency).

Here is our test:

/// <reference path="../../../scripts/jquery-2.1.3.min.js" />
/// <reference path="../../../scripts/jasmine/jasmine.js" />
/// <reference path="../../../scripts/angular.min.js" />
/// <reference path="../../../scripts/angular-mocks.js" />
/// <reference path="../../hangman/hangmanBundle.js" />

describe("Hangman Service - unit:", function () {
    describe("When the service is created", function () {
        var target;
 
        //Mock objects
        var mockHangmanConstants = {
            NS: window.hangman,
            MAX_ERRORS: 5
        };
 
        beforeEach(function () {
 
            //Create a mock module with our
            //mock objects. The dependencies
            //will be all taken from here
            module(function ($provide) {
                $provide.value("hangmanConstants", mockHangmanConstants);
            });
 
            //Load the module to test
            module("hangmanApp.services");
            inject(function ($injector) {
 
                //Resolve the hangmanService
                target = $injector.get("hangmanService");
            });
        });
 
        it("It should return a keyboard", function () {
            var keyboard = target.getKeyboard();
            expect(keyboard).toBeDefined();
        });
 
        it("It should return a phrase", function () {
            var phrase = target.getPhrase("The Test Phrase");
            expect(phrase).toBeDefined();
        });
    });
});
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s