【问题标题】:Jasmine + karma + angular test create controllerJasmine + 业力 + 角度测试创建控制器
【发布时间】:2016-03-05 10:23:53
【问题描述】:

我在哪里犯错了?如何在 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)

【问题讨论】:

    标签: javascript angularjs jasmine karma-jasmine


    【解决方案1】:

    你在这里错过了几件事

    1. 您需要初始化 Angular 模块,以使您的控制器和所有其他组件可用,方法是在每个之前执行 module('myApp.contact'),以便 Error: [ng:areq] Argument 'contactCtrl' is not a function, got undefined 消失。
    2. 然后在您的 Assert 测试语句中,您应该使用 scope 对象而不是 controller(当您的属性绑定到 this 时,您可以使用控制器)
    3. 别忘了在页面上引用contactCtrl.jsui-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
        });
    });
    

    【讨论】:

    • 模块(myApp.contact);说 myApp 未定义,我尝试将其更改为 module('myApp.contact');错误:注入器已创建,无法注册模块!在 karma.conf.js 我包含所有文件
    • @PeterPan 用单引号括起来,我错过了那个
    • 我第一次包装它,但抛出:错误:注射器已创建,无法注册模块!
    • @PeterPan 发生这种情况是因为我们在 beforeEach 内部使用了 function inject(),在模块初始化之前,我们应该先加载 Angular 模块。
    • 好的,我该怎么做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多