窥探递归角度控制器方法

Spying on recursive Angular controller method

本文关键字:控制器 方法 递归      更新时间:2023-10-04

我有一个递归方法,如果设置了标志,它将每五秒钟调用一次自己。我正试图编写一个测试,监视该方法,调用它,等待六秒钟,然后期望该方法被调用两次。我的测试失败了,因为间谍报告该方法只被调用一次(初始调用)。

我使用的是Angular样式指南,所以将这些方法附加到this的占位符中。我怀疑从角度模拟$controller()返回的控制器的作用域可能存在问题,但我不确定——大多数人都将方法附加到$scope

如果不将方法附加到$scope,我如何创建一个间谍来验证我的方法是否被调用了两次?

app.js:

'use strict';
angular
    .module('MyApp', [
        //...
    ]);
angular
    .module('MyApp')
    .controller('MyController', MyController);
MyController.$inject = [
    //...
];
function MyController() {
    var vm = this;
    vm.callMyself = callMyself;
    vm.flag = false;
    function callMyself () {
        console.log('callMyself');
        if (vm.flag) {
            console.log('callMyself & flag');
            setTimeout(vm.callMyself, 5000);
        }
    }
}

appSpec.js:

describe('MyController', function () {
    var $scope;
    beforeEach(function () {
        module('MyApp');
    });
    beforeEach(inject(function($rootScope, $controller) {
        $scope = $rootScope.$new();
        controllerInstance = $controller('MyController', {$scope: $scope});
    }));
    it('should call itself within 6 seconds if flag is true', function (done) {
        controllerInstance.flag = true;
        spyOn(controllerInstance, 'callMyself');
        controllerInstance.callMyself();
        setTimeout(function () {
            expect(controllerInstance.callMyself).toHaveBeenCalledTimes(2);
            done();
        }, 6000);
    }, 7000);
});

工作Plunker

您需要使用.and.callThrough()来进一步执行将调用自己的函数:

通过将spy与and.callThrough链接,spy仍将跟踪对它的所有调用,但除此之外,它将委托给实际实现

spyOn(controllerInstance, 'callMyself').and.callThrough();

在plunker中测试-它有效。