简体   繁体   English

如何在我的子控制器中模拟此方法来测试它?

[英]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.

相关问题 如何在控制器中测试功能? - how can I test functions in my controller? 如何模拟一个“ instanceof”测试? - How can I mock an `instanceof` test? 如何将Angular控制器注入单元测试 - How can I inject an Angular controller into my unit test Angular Controller Mock 在我的 Mocha 测试中不存在 - Angular Controller Mock is not perisisting in my Mocha test 如何在我的Karma / Mocha测试套件中测试Angular 1.5控制器? - How can I test my Angular 1.5 controller in my Karma/Mocha test suite? 如何将商品ID传递给我的控制器以使用删除方法? - How can I pass an item id to my controller for deletion method? 我将如何在我的 controller 中模拟 axios 电话? - How would I mock the axios call in my controller in express? 为我的每个 React 组件添加了一个导航栏,我如何在测试中模拟导航栏,因为所有测试都失败,因为导航栏组件中的方法调用是 null? - Added a navbar to each of my React components, how do I mock the navbar in test as all tests failing as a method call in Navbar component is null? 如何在玩笑反应测试中模拟此功能? - How can I mock this function in jest react test? 如何将模拟服务注入过滤器的单元测试? - How can i inject a mock service into a unit test for a filter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM