2

I've just started wading through unit and end-to-end testing for an angular app.

I'm confused as to where I should declare the ngMock and ngMocke2e modules. My bower.json file has the reference to ngMock, and the index.html file is pointing to angular-mocks.js script.

However, when I declare ngMock in the dependencies of my app.js, the application won't load. Furthermore, there are no errors displayed in the console.

I need to use these modules for testing, but it seems counter-intuitive to inject them into the app from app.js.

Tony Barnes
  • 2,625
  • 1
  • 18
  • 29
abyrne85
  • 1,370
  • 16
  • 33

2 Answers2

2

You don't need to add angular-mocks to your main app.js You need to inject angular-mocks into your karma conf, which is the only place that needs it.

For example:

module.exports = function(config) {
  'use strict';

  config.set({

    files: [
      'bower_components/angular/angular.js',
      'bower_components/angular-resource/angular-resource.js',
      ...
      'bower_components/angular-mocks/angular-mocks.js'
      ...

    ]

  });
};
Tony Barnes
  • 2,625
  • 1
  • 18
  • 29
  • Thanks Tony. Just to put a source on the confusion, I'm working from the angular docs : link. It says it needs to be included as a dependant module : `angular.module('app', ['ngMock'])`; – abyrne85 Apr 23 '15 at 16:36
  • @abyrne85 pleasure! The angular docs aren't the best... I think there are a few ways you can use it - in the docs it's injecting straight into the 'regular' module declaration in the app, but for your case, with karma, only karma needs it - you don't need it in the app. It's for testing purposes only - to help you inject angular services into your tests. Personally I haven't seen it injected anywhere other than the karma conf. – Tony Barnes Apr 23 '15 at 16:42
2

As noted in the answer from Tony Barnes, you can register the ngMock source file in the karma config.

For a little more depth on how this works; once ngMock's inject function is called for the first time, it performs a bootstrap of the app and automatically includes 'ng' and 'ngMock' modules along with the module(s) registered for our unit tests.

This is why we don't need to write code along the lines of angular.module('app', ['ngMock']) in order to setup our tests, but it also feels little magical since it's not obvious that this bootstrapping step is done for us.

I've written a number of AngularJS Unit Testing Tutorials, such as ngMock Fundamentals for AngularJS - Understanding Inject that go into more depth on concepts of gnomic.

Bradley Braithwaite
  • 1,122
  • 2
  • 19
  • 22