简体   繁体   中英

Injecting angular js service/factory into Jasmine

I am trying to run some Jasmine Unit test on a factory I have created in Angular JS.

Here is my app.js

var app = angular.module('myApp', [
    'ngRoute'
]);

Here is the services.js

app.factory('Service', function(){
    var service = {
        one: function(){
            return 1;
          }
      };
    return service;
  })

Here is the Karma conf file

  files: [
      'public/bower_components/angular/angular.js',
      'public/bower_components/angular-mocks/angular-mocks.js',
      'public/js/app.js',
      'public/js/controllers.js',
      'public/js/services.js',
      'test/**/*test.js'
    ],

And here is the test

'use strict';

(function () {

    describe('myApp', function () {

      beforeEach(module('myApp'));

      it('testing the service', inject(function (Service) {
        console.log(Service)
      }));

    });
})();

I am really stuck and don't know which way to go now :( All the correct scripts are loaded into the browser. Also the app works in normal mode in the browser, so the Service factory is fine.

The error message say:

Error: [$injector:modulerr] Failed to instantiate module myApp due to:
    Error: [$injector:modulerr] Failed to instantiate module ngRoute due to:
    Error: [$injector:nomod] Module 'ngRoute' 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.

The problem is exactly what the message says: ngRoute is not available, because you haven't included that script in the your Karma config file. You need to add a line like this to the the files array:

'public/bower_components/angular-route/angular-route.js',

I don't know offhand what the path is, so you may need to tweak that.

Just to help some people along, the way to view setup Karma testing is similar to how you would setup you index.html.

In the index.html you would ensure all the scripts you needed were loaded and loaded int he right order.

In the same way when you setup Karma it needs to know what scripts to use.

So you ensure the file section is populated with the right scripts!

 files: [
      'public/bower_components/angular/angular.js',
      'public/bower_components/angular-mocks/angular-mocks.js',
      'public/js/app.js',
      'public/js/controllers.js',
      'public/js/services.js',
      'test/**/*test.js'
    ],

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM