如何单元测试一个函数在我的情况下

How to unit test a function in my case

本文关键字:函数 一个 我的 情况下 单元测试      更新时间:2023-09-26

我正在尝试为子控制器创建单元测试在子控制器中,我调用了父

中的一个函数

子控制器

$scope.clickMe = function(){
    $scope.parentMethod();
})
父控制器

$scope.parentMethod = function(item){
    //do something with parent
})
单元测试

var childCtrl;
 beforeEach(module('myApp'));
    beforeEach(inject(function (_$controller_, _$rootScope_) {
        scope        = _$rootScope_.$new();
        childCtrl = _$controller_('childCtrl', {
            $scope: scope
        });
    }));
    describe('test parent', function() {
        it('should call parent', function() {
            $scope.clickMe();
            $httpBackend.flush();
        });
    });
});

I am getting

TypeError: 'undefined' is not a function (evaluating '$scope.parentMethod()')

我不知道如何解决这个问题。有人能帮我一下吗?非常感谢!

为了测试子控制器

,您应该在作用域中模拟该方法
    scope        = _$rootScope_.$new();
    scope.parentMethod = function noop(){};
    childCtrl = _$controller_('childCtrl', {
        $scope: scope
    });

对于测试noop应该用spy代替。语法将取决于您使用的引擎Jasmine或Sinon。这样,在测试中就可以验证parentMethod是否被调用了。