[英]Getting method as undefined while running karma test
I have created a scope method inside my controller which is executing when a button is pressed. 我在我的控制器中创建了一个范围方法,该方法在按下按钮时执行。 I am writing unit test cases for the same.
我正在编写相同的单元测试用例。 I have injected my module in beforeEach block and created spyon my scope function and then using it in 'it' method and checking whether it is called or not.
我在beforeEach块中注入了我的模块并创建了spyon我的scope函数,然后在'it'方法中使用它并检查它是否被调用。 But getting an error as a method not found.
但是找不到错误的方法。
Controller 调节器
'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 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);
});
});
});
Need help to resolve this issue. 需要帮助来解决此问题。
It looks like you're trying to spy on the showFormData method of the controller: 看起来你正试图窥探控制器的showFormData方法:
spyOn(controller, 'showFormData');
However, the showFormData doesn't exist on the controller, it's a method of the controller's scope. 但是,showFormData在控制器上不存在,它是控制器范围的一种方法。
You'll need to use: 你需要使用:
spyOn($scope, 'showFormData');
It's also important to know that you need to use the same object to both spyOn and expect(...).toHaveBeenCalled(). 知道你需要对spyOn和expect(...)。toHaveBeenCalled()使用相同的对象也很重要。 In your case you where spying on controller.showFormData(), yet expecting $scope.showFormData() to have been called.
在你的情况下,你监视controller.showFormData(),但期望调用$ scope.showFormData()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.