Jasmine JS, Angular JS – Testing of an Angular Service

In this situation we don’t have to manage with templates, as we had to do with the directives, so we just use the $injector.get() method (within the inject() method as always) to ask angular to resolve the service that we want to test for us.

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 - integration:", function () {
    describe("When the service is created", function () {
        var target;
 
        beforeEach(function () {
 
            //Load the module to test
            //and its dependency modules
            module("hangmanApp.constants");
            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();
        });
    });
});

Here’s our service’s code

angular.module("hangmanApp.services").service("hangmanService",
    ["hangmanConstants", function (hangmanConstants) {
        var _this = this;
 
        _this.getKeyboard = function () {
            return new hangmanConstants.NS.KeyboardModel();
        };
        _this.getPhrase = function (phrase) {
            return new hangmanConstants.NS.PhraseModel(phrase);
        };
    }]);
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