Unit Testing Services in AngularJS with Jasmine, Karma and ng-Mock

Issue

I’m having trouble accessing my services and filters in unit tests (I haven’t tried directives yet). I’ve written unit tests before, but as I have moved to the configuration of our builds, I’m having trouble accessing our new services to write unit tests. I’m continually getting TypeError: null is not an object (evaluating 'currentSpec.$modules') in.... I did some reading and it looks like it may have to do with the node packages I’m using. I was wondering if the greater community could make sure these configurations look correct. I’ve abbreviated the files below.

With the current config, this is erroring out.

package.json

"devDependencies": {
  "angular": "1.5.7",
  "angular-mocks": "1.5.7",
  "jasmine": "2.4.1",
  "jasmine-core": "2.4.1",
  "karma-browserify": "5.1.0",
  "karma-chrome-launcher": "1.0.1",
  "karma-jasmine": "1.0.2",
  "karma-nyan-reporter": "0.2.4",
  "karma-phantomjs2-launcher": "0.5.0",
  "phantomjs2": "2.2.0"
}

karma.conf.js

module.exports = function(config) {
  config.set({

    basePath: '',

    frameworks: ['browserify', 'jasmine'],

    files: [
      'app/main.js',
      'app/modules/**/*.spec.js',
      'app/shared/**/**/*.spec.js'
    ],

     preprocessors: {
       'app/main.js': ['browserify'],
       'app/modules/index.js': ['browserify'],
       'app/shared/index.js': ['browserify'],
       'app/modules/**/*.spec.js': ['browserify'],
       'app/shared/**/**/*.spec.js': ['browserify']
     },
  })
}

service.spec.js

describe('Unit: Services', function() {
  require('angular-mocks/ngMock');

  var APIHelper;

  beforeEach(function() {
    angular.mock.module('app.common.services');
  });

  beforeEach(inject(function(apiHelperService) {
    APIHelper = apiHelperService; //injection is what's breaking
  }));

  it('should exist', function() {
    expect(APIHelper).toBeDefined();
  });

});

The services and specs are being loaded and in the correct order. This service has no dependencies. I’m assuming I’ll be getting the same errors when I need to inject service dependencies, but if I can get the injections figured out, I can inject the proper services as I need them.

// This worked in a controller
angular.mock.inject(function GetDependencies(service) {
  service = service;
});

Thank you in advance for taking the time to look over this and potentially answering a question.

-W

Solution

I wasn’t including require('angular-mocks/ngMock') in my app declaration. Sometimes, it’s the little things.

Answered By – bigjollygiant14

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.