user687554
user687554

Reputation: 11131

Loading AngularJS module in Jasmine test via Grunt

I am trying to write some unit tests for an AngularJS service. I want to run the unit tests from the command-line via Grunt. In an attempt to do that, I've written the following:

gruntfile.js

'use strict';
module.exports = function (grunt) {
    grunt.initConfig({
        jasmine: {
            service: {
                src: 'dist/myService.js',
                options: {
                    specs: 'test/*.js',
                    vendor: [
                        'bower_components/angularjs/angular.min.js',
                        'bower_components/angular-mocks/angular-mocks.js'
                    ]
                }
            }
        }
    });

    // load all grunt task details
    require('load-grunt-tasks')(grunt);

    grunt.registerTask('default', ['jasmine:service']);    
};

dist/myService.js

'use strict';
angular.module('myModule')
    .factory('$myService', function () {    
        return {    
            getResult: function () {
                return 3;
            }
        };
    })
;

test/serviceTests.spec.js

describe('myModule', function() {
    beforeEach(function() {
        console.log('loading module...');
        module('myModule');
    });

    describe('$myService', function () {
        it('should work', function () {
            console.log('testing');
            expect(1 + 2).toEqual(3);
        });
    });
})

When I try to run this, I get the following error:

Running "jasmine:service" (jasmine) task
Testing jasmine specs via PhantomJS

>> Error: [$injector:nomod] http://errors.angularjs.org/1.2.22/$injector/nomod?p0=myModule at
>> ..\..\..\C:\source\myModule\bower_components\angularjs\angular.min.js:20
>> ..\..\..\C:\source\myModule\bower_components\angularjs\angular.min.js:21
>> ..\..\..\C:\source\myModule\dist\myService.js
 myModule
   $myService
     - should work...
log: loading module...

log: testing
     √ should work

I know that in order to test my service, I need to inject it. However, at this time, I'm getting an error loading the module itself. For that reason, I know that I cannot inject my service. However, I do not know why the module won't load. I've confirmed that I have the correct src value.

Can anybody tell me what I'm doing wrong? Or, perhaps point me to the smallest possible example of testing a service in AngularJS (complete with Grunt, etc.)?

I just don't understand what is wrong with my approach. Thank you for your help.

Upvotes: 1

Views: 171

Answers (1)

Alexander Puchkov
Alexander Puchkov

Reputation: 5973

When you call angular.module('myModule') (without second parameter) Angular tries to reference already existing module and cannot find it.

To declare a new module you should call angular.module('myModule', []) (with two parameters)

Upvotes: 1

Related Questions