Search code examples
angularjskarma-runnerangularjs-injector

Inject a module into karma test in Angular 1.5


I am trying to upgrade my Angular app from 1.3.x to 1.5.1. I have a suite of tests that all ran fine with Karma + PhantomJS when I was at version 1.3.x of Angular, however once I upgraded all of my tests are failing. It appears that the way I was injecting modules into the unit tests before no longer works.

This fails in 1.5:

'use strict'
 App = null

 fdescribe 'App Model', ->
   beforeEach module('MyAngularApp')

   beforeEach inject ($injector)->
     App = $injector.get('App')

 it 'should exist', ->
   console.log 'App:', App
   expect(App).toBeDefined()

I have also tried injecting with the following

 beforeEach inject ($injector, _App_)->
   App = _App_

but my App model is still not being injected.

I have been digging through the documentation on AngularJS 1.5.1 but I didn't see any changes that I need to make with the injector.

In Angular 1.5.x, how can I properly inject a model into my unit tests?


Solution

  • Ok so it looks like the issue was actually that the upgrade caused a second copy of angular-mocks to be bundled up into the app. I'm not sure whether this came from AngularJS, Karma, or PhantomJS but removing the angular-mock.js file from the files included in the configuration of karma.conf.js fixed the issue. It seems like the PhantomJS error logs just didn't provide enough insight into what the actual issue was.

    For anyone else experiencing this issue, I noticed that changing the browser I was testing in to Chrome (instead of PhantomJS 2) resulted in a different error message:

    Error: [$injector:modulerr] Failed to instantiate module ng due to:
    Error: [$injector:modulerr] Failed to instantiate module ngLocale due to:
    RangeError: Maximum call stack size exceeded
    

    That lead me to the solution here: https://github.com/angular/angular.js/issues/11303