Jasmine + karma + angular 测试创建控制器

Jasmine + karma + angular test create controller

我哪里弄错了?如何在 Jasmine + angular 中获取控制器实例?我该如何解决控制器?我不知道我应该用什么来解决这个问题。

'use strict';

angular.module('myApp.contact', ['ui.router'])
.controller('contactCtrl', ['$scope', function ($scope) {
    $scope.contact = {
        name: 'John Doe'
    };
}]);


describe('myApp.contact module tests', function () {
    var scope, createController;

    beforeEach(inject(function ($rootScope, $controller) {
        scope = $rootScope.$new();

        createController = function () {
            return $controller('contactCtrl', {
                '$scope': scope
            });
        };
    }));

    it('contact name is John Doe', function () {
        var controller = createController();
        expect(controller).toEqual('John Doe');
    });
});

myApp.contact module tests
    ✗ contact name is John Doe
        Error: [ng:areq] Argument 'contactCtrl' is not a function, got undefined
        http://errors.angularjs.org/1.4.9/ng/areq?p0=contactCtrl&p1=not%20a%20function%2C%20got%20undefined
            at E:/angular-seed/app/bower_components/angular/angular.js:68:12
            at assertArg (E:/angular-seed/app/bower_components/angular/angular.js:1816:11)
            at assertArgFn (E:/angular-seed/app/bower_components/angular/angular.js:1826:3)

你在这里错过了一些东西

  1. 您需要初始化 angular 模块以使您的控制器和所有其他组件可用,方法是在每个之前执行 module('myApp.contact') 以便 Error: [ng:areq] Argument 'contactCtrl' is not a function, got undefined 消失。
  2. 然后在你的 Assert 测试语句中你应该使用 scope 对象而不是 controller(当你的属性绑定到 this 时你可以使用控制器)
  3. 不要忘记参考页面上的 contactCtrl.js & ui-router.js

    expect(scope.contact.name).toEqual('John Doe');
    

代码

describe('myApp.contact module tests', function () {
    var scope, createController;
    beforeEach(module('myApp.contact')); //1st change

    beforeEach(inject(function ($rootScope, $controller) {
        scope = $rootScope.$new();
        createController = function () {
            return $controller('contactCtrl', {
                '$scope': scope
            });
        };
    }));

    it('contact name is John Doe', function () {
        var controller = createController();
        expect(scope.contact.name).toEqual('John Doe'); //2nd change
    });
});