Search code examples
angularjsunit-testingkarma-jasminejasmine2.0angular-factory

Jasmine 2.0 unit testing for angularjs factory


I am new to writing jasmine test cases for angularJS factory. I want to test the entire factory, but I'm unable to fetch getKeys. Here's my factory.

My Factory is:

'use strict';
var a11yModule = angular.module('TestModule', ['ui.bootstrap']);
a11yModule.factory('TestFacotry', ['$q', '$timeout', function ($q, $timeout) {
    return {
        getKeys: function () {
            return {
                "abc": 32,
                "gpa": 33,
                "end": 35
            };
        }
    };
}])

My Unit Spec is:

describe('modu testing', function () {
    var TestFacotryMock, q, timeout;
    beforeEach(module('TestModule', ['ui.bootstrap']));

    beforeEach(inject(function (_$q_, _$timeout_, _TestFacotry_) {
        q = _$q_;
        timeout = _$timeout_;
        TestFacotryMock = _TestFacotry_;

    }));

    it('Should ', function () {
        //var output = TestFacotryMock.getKeys.something();
        expect(typeof getKeys()).toBe('function');
    });

});

Error is

Error: [$injector:modulerr] Failed to instantiate module TestModule due to: Error: [$injector:modulerr] Failed to instantiate module ui.bootstrap due to: Error: [$injector:nomod] Module 'ui.bootstrap' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.


Solution

  • jamin needs to be referenced before angular modules in index.html because angular-mock library has dependency over jasmin.

    load the libraries like jasmin angular,angular-mock from local folder instead from web

    .

    <link data-require="jasmine" data-semver="1.3.1" rel="stylesheet" href="http://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css">
    <script data-require="jasmine" data-semver="1.3.1" src="http://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
    <script data-require="jasmine" data-semver="1.3.1" src="http://cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>        
    <script data-require="angular.js" data-semver="1.1.5" src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
    <script data-require="angular-resource.js" data-semver="1.1.5" src="http://code.angularjs.org/1.1.5/angular-resource.min.js"></script>
    <script data-require="angular-mocks" data-semver="1.1.5" src="angular-mocks.js"></script>
    <link rel="stylesheet" href="style.css">
    <script src="jasmineBootstrap.js"></script>
    <script src="script.js"></script>
    <script src="addSpec.js"></script>
    

    some mistake in unit test

    it('Should ', function () {
    
        expect(typeof TestCommonMock.getKeys()).toBe('object');
    });