[英]How can I mock this method in my child controller to test it?
I have this angular controller that has a method 我有这个角度控制器有一个方法
$scope.handleChange = function (index) {
//Logic
$scope.$parent.doSomething();
};
I can't seem to find ways to test the handleChange()
method OR the controller object with jasmine, as both tests throw this error: TypeError: $scope.$parent.doSomething is not a function
我似乎无法找到测试
handleChange()
方法或使用jasmine的控制器对象的方法,因为两个测试都抛出此错误: TypeError: $scope.$parent.doSomething is not a function
I've done this: 我这样做了:
beforeEach(inject(function ($controller, $injector, $q, $rootScope) {
var qReference = $q;
var rootScopeReference = $rootScope;
var $scope = rootScopeReference.$new();
var controllerReference = $controller('MyController', {
$scope: $scope
});
}));
it('Test Case-1: Mycontroller is defined', function () {
expect(controllerReference).toBeDefined();
});
What am I doing wrong and how can I solve this? 我做错了什么,怎么解决这个问题?
You can just store the scope in a variable in your test class, mock the method doSomething using a spy: 您可以将范围存储在测试类的变量中,使用间谍模拟方法doSomething:
var myScope = $rootScope.$new();
spyOn(myScope.$parent, 'doSomething');
Then pass it to your controller: 然后将其传递给您的控制器:
var controllerReference = $controller('MyController', {
$scope: myScope
});
And on your assertion block you do something like this: 在你的断言块你做这样的事情:
expect(myScope.$parent.doSomething).toHaveBeenCalled();
Hope that helps. 希望有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.