javascript - Jasmine + karma + Angular Testing 创建 Controller

标签 javascript angularjs jasmine karma-jasmine

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

'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 模块以使您的 Controller 和所有其他组件可用,方法是在每个之前执行 module('myApp.contact') 以便 Error: [ng:areq ] 参数“contactCtrl”不是函数,未定义 将消失。
  2. 然后在你的 Assert 测试语句中,你应该使用 scope object 而不是 controller(当你的属性绑定(bind)到 this 时,你可以使用 controller >)
  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
    });
});

关于javascript - Jasmine + karma + Angular Testing 创建 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35812922/

相关文章:

javascript - 如何在 TensorFlow.js 中使用 optimize.minimize 和最大池化层

javascript - AngularJS 初始化 Controller 变量

javascript - Jasmine 测试 Backbone,Scoping 问题

reactjs - React Enzyme 找到第二个(或第 n 个)节点

javascript - 类型错误 : undefined is not a function

javascript - Google 图表对象错误 : google not defined

javascript - kinetic js,我怎样才能提高元素的分辨率

javascript - 为 React js 编写测试时如何模拟浏览器事件?

javascript - 从 AngularJS 中的文本文件获取 Json 数据

css - 具有背景颜色样式的 div 容器的不透明度