我是使用 Jasmine 测试 Angular Apps 的新手,我无法弄清楚这个问题的原因......
Controller
programsModule.controller('ticketCtrl', ['$scope', function ($scope) {
$scope.disableSendBtn = true;
});
这是单元测试
'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);
});
});
});
这是测试的输出
TypeError: Cannot read property 'disableSendBtn' of undefined
如果我测试 $scope
变量是否被定义
it('Should $scope be defined', function () {
expect($scope).toBeDefined();
});
我也有这个错误
Expected undefined to be defined.
那么这里有什么问题呢?
这是 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
最佳答案
Error: [ng:areq] Argument 'ticketCtrl' is not a function, got undefined
当尝试实例化您在 beforeEach 函数中初始化的模块中未定义的 Controller 时,通常会抛出此错误。
提供的代码看起来不错。唯一缺少的是检查 karma 是否成功找到您的文件。打开您的 karma.conf.js 文件并确保定义 Controller 的文件在正则表达式中列出或使用正则表达式拾取。
关于javascript - 在使用 Jasmine 测试 Angular Controller 时预期未定义被定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30970482/