![](/img/trans.png)
[英]Angular Karma Test getting “TypeError: 'undefined' is not a function”
[英]Getting method as undefined while running karma test
我在我的控制器中创建了一个范围方法,该方法在按下按钮时执行。 我正在编写相同的单元测试用例。 我在beforeEach块中注入了我的模块并创建了spyon我的scope函数,然后在'it'方法中使用它并检查它是否被调用。 但是找不到错误的方法。
调节器
'use strict';
angular.module('myApp.view1', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
});
}])
.controller('View1Ctrl', ['$scope',View1Ctrl])
function View1Ctrl($scope) {
$scope.user = {
name: '',
last: ''
}
$scope.showFormData = function() {
$scope.formData = $scope.user.name + $scope.user.last;
}
}
spec.js
'use strict';
describe('myApp.view1 module', function () {
var $controller, $rootScope;
beforeEach(module('myApp.view1'));
beforeEach(inject(function (_$controller_, _$rootScope_) {
$controller = _$controller_;
$rootScope = _$rootScope_;
}));
describe('view1 controller', function () {
var $scope, controller, formData;
beforeEach(function () {
$scope = $rootScope.$new();
controller = $controller('View1Ctrl', {
$scope: $scope
});
spyOn(controller, 'showFormData');
});
it('should check for the show form details', function () {
$scope.user.name = "Sandeep";
$scope.user.last = "Gupta";
expect($scope.showFormData).toHaveBeenCalled();
expect($scope.user.name + $scope.user.last).toEqual(firstname);
});
});
});
需要帮助来解决此问题。
看起来你正试图窥探控制器的showFormData方法:
spyOn(controller, 'showFormData');
但是,showFormData在控制器上不存在,它是控制器范围的一种方法。
你需要使用:
spyOn($scope, 'showFormData');
知道你需要对spyOn和expect(...)。toHaveBeenCalled()使用相同的对象也很重要。 在你的情况下,你监视controller.showFormData(),但期望调用$ scope.showFormData()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.