Ankit Prajapati
Ankit Prajapati

Reputation: 1473

Testing Angular Service with Jasmine: Failed to instantiate module app

I am trying to create a Simple Unit Test using Jasmine for an Angular Service. But when I am running the Test via Karma, I am getting the following error:

Failed to instantiate module app

And I don't know why I am getting this error. I Googled and tried to apply the below solutions. But none worked.

But the error remains the same.

It is a very simple code. Please find the code below for reference:

string.service.js

(function () {
    "use strict";

    angular
        .module('app')
        .factory("stringService", stringService)

    function stringService() {

        return {
            checkForAlphaNumeric: checkForAlphaNumeric,
        };

        function checkForAlphaNumeric(string) {
            var regex = /^[a-zA-Z0-9]+$/;
            return regex.test(string);
        }
    }
})();

string.service.spec.js

describe("-----> String Service", function () {

    var stringService;
    beforeEach(function () {
        angular.mock.module('app');
        inject(function ($injector) {
            stringService = $injector.get('stringService');
        });
    });

    it("--> stringService should be Defined.", function () {
        expect(stringService).toBeDefined();
    });
});

karma.conf.js

// list of files / patterns to load in the browser
files: [
  //External
  './node_modules/angular/angular.js', // Angular Framework
  './node_modules/angular-mocks/angular-mocks.js', // Loads the Module for Tests
  './node_modules/@uirouter/angularjs/release/angular-ui-router.js', // UI-Router
  './node_modules/angular-route/angular-route.js',

  //Sub Modules
  './app/authentication/authentication.module.js',

  //Main Module
  './app/app.module.js', // Angular App

  //Controllers
  './app/authentication/login.controller.js',

  //Services and Factories
  './app/services/string.service.js',

  //Specs
  './app/licensing/licensing.controller.spec.js',
  './app/services/string.service.spec.js'
],

Any help will be greatly appreciated.

Upvotes: 1

Views: 730

Answers (1)

Ankit Prajapati
Ankit Prajapati

Reputation: 1473

I have figured out what was wrong in my scenario. Let me explain:

  • My app module has several dependencies.
  • My string service was part of app module.
  • Now, when you want to test the string service, you have to reference all (means all) the app module dependencies in the karma.conf.js file section. Even the ones you are not using for the service.
  • In my case, I was not referencing the qrcode dependency as I was not using qrcode in the string service.
  • And this missing reference was creating the problem. And hence the karma was not able to instantiate the module app.

Hope this helps somebody.

Upvotes: 1

Related Questions