在使用Jasmine测试角度控制器时,预期未定义

Leo*_*ref 5 javascript jasmine angularjs

我是用Jasmine测试Angular Apps的新手,我无法弄清楚这个问题的原因......

控制器

programsModule.controller('ticketCtrl', ['$scope', function ($scope) {
    $scope.disableSendBtn = true;
});
Run Code Online (Sandbox Code Playgroud)

这是单元测试

'use strict';

describe('app', function () {

    // variables
    var $rootScope, $scope, $controller;

    beforeEach(module('supportModule'));

    describe('ticketCtrl', function () {
        beforeEach(inject(function (_$rootScope_, _$controller_) {
            $rootScope = _$rootScope_;
            $scope = $rootScope.$new();
            $controller = _$controller_('ticketCtrl', {
                '$scope': $scope
            });
        }));

        it('Should disable send btn', function () {
            expect($scope.disableSendBtn).toEqual(true);
        });

    });    
});
Run Code Online (Sandbox Code Playgroud)

这是测试的结果

TypeError: Cannot read property 'disableSendBtn' of undefined
Run Code Online (Sandbox Code Playgroud)

如果我测试$scope变量是否定义了

it('Should $scope be defined', function () {
    expect($scope).toBeDefined();
});
Run Code Online (Sandbox Code Playgroud)

我也得到这个错误

Expected undefined to be defined.
Run Code Online (Sandbox Code Playgroud)

那么这里的问题是什么?

这里是jsFiddle http://jsfiddle.net/LeoAref/bn1wxycs/


编辑

我这里使用了错误的模块 beforeEach(module('app'));

我通过使用正确的模块修复了这个问题 beforeEach(module('supportModule'));

我又得到了一个错误:

Error: [ng:areq] Argument 'ticketCtrl' is not a function, got undefined
http://errors.angularjs.org/1.4.1/ng/areq?p0=ticketCtrl&p1=not%20a%20function%2C%20got%20undefined
Run Code Online (Sandbox Code Playgroud)

S.K*_*ski 0

错误:[ng:areq] 参数“ticketCtrl”不是函数,未定义

当尝试实例化未在 beforeEach 函数中初始化的模块中定义的控制器时,通常会引发此错误。

提供的代码看起来不错。唯一缺少的是检查 karma 是否成功找到您的文件。打开 karma.conf.js 文件并确保定义控制器的文件已在正则表达式中列出或使用正则表达式选取。