简体   繁体   中英

How can I inject an Angular controller into my unit test

I'm really hoping this is a trivial issue. Yes, I have RTFM. I'm actually using the Angular documented way to inject a controller, but for some reason my controller is not defined. The main difference here is that I'm used to working on single module apps and this time I have a multi module app. I wouldn't think it would make a difference, but there you go. Instead of a lengthy description, I'll get straight to the code:

Using Angular 1.2.16

Unit Test Framework: Jasmine

app.js

 angular.module('OBB', [
  // Native AngularJS DI
  'ngResource', 'ngCookies', 

  // bunch of modules
  ...

  // OBB Page Modules
  'OBB.home', 'OBB.buckets', 'OBB.company', 'OBB.advSearch', 'OBB.users'
])

So, I'm trying to test a controller in the OBB.home module.

home.js

angular.module('OBB.home', ['ui.router'])
.controller('HomeCtrl', ['$log', '$rootScope', '$scope', '$state', 'AUTH_EVENTS',  
  function HomeCtrl ($log, $rootScope, $scope, $state, AUTH_EVENTS) {
    $scope.signInFormData = {
      email: null, password: null
    };
    //more code...
}]);

home.spec.js

describe('Unit Home Controllers: ', function () {

  var homeController, scope;

  beforeEach(module('OBB.home'));

  beforeEach(inject(function (_$rootScope_, $controller) {
      scope = _$rootScope_.$new();
      homeController = $controller('HomeCtrl', {
        $rootScope: _$rootScope_,
        $scope: scope,
        $log: {},
        $state: {},
        AUTH_EVENTS: {},
      });
    }));

  it('Home Controller is correctly instantiated', inject(function () {
    expect(scope).toBeDefined();  // Pass
    expect(scope.signInFormData).toBeDefined();  // Fails
  }));
});

You need to mock/load your dependencies.

describe('Unit Home Controllers: ', function () {

  var homeController, scope;

  beforeEach(module('OBB.home'));

  beforeEach(inject(function (_$rootScope_, $controller) {
      scope = _$rootScope_.$new();
      homeController = $controller('HomeCtrl', {
        $rootScope: _$rootScope_,
        $scope: scope,
        $log: {},  //You will have to add methods as needed
        $state: {},
        AUTH_EVENTS: {}
      });
    }));

  it('Home Controller is correctly instantiated', inject(function () {
    expect(scope).toBeDefined();  // Fails
    expect(scope.signInFormData).toBeDefined();  // Fails
  }));
});

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