Angular 服务在 spyOn 时变得未定义

Angular Service becomes undefined when spyOn it

我有一个 Angular 1.6.6 应用程序,我正在使用 Karma 和 Jasmine 对其进行测试。

给出来自控制器的代码:

    $scope.undo = function () {
        return $scope.isUndoDisabled() || $scope.undoAction();
    };

    $scope.isUndoDisabled = function () {
        return HistoryService.isUndoDisabled();
    };

我一直在使用以下规格对其进行测试:

it('undoAction should not be called with default settings', function () {
        var $scope = {};
        var controller = $controller('PaintController', { $scope: $scope });

        spyOn($scope, 'undoAction');
        //spyOn(HistoryService, 'isUndoDisabled');

        $scope.undo();
        expect($scope.undoAction).not.toHaveBeenCalled();
    });

并且通过了测试,但是当我取消注释 HistoryService 的 spyOn 时,来自 $scope.isUndoDisabled returns 的调用 HistoryService.isUndoDisabled() 未定义并且那么测试 失败 因为:

Expected spy undoAction not to have been called.

知道发生了什么事吗????似乎 spyOn 正在影响代码??

我想如果你想从 HistoryService 调用 isUndoDisabled(),函数 $scope.isUndoDisabled 应该是

 $scope.isUndoDisabled = function () {
    HistoryService.isUndoDisabled();
};

正文中不应该有return

spyOn(...)spyOn(...).and.stub() 的快捷方式,而不是 spyOn(...).and.callThrough()。这样被窥探时,HistoryService.isUndoDisabled() returns undefined.

测试单元的正确方法是将它与其他单元隔离开来。由于是被测试的controller,服务应该被mock或者stubbed:

spyOn(HistoryService, 'isUndoDisabled').and.returnValue(true);

然后在另一个测试中:

spyOn(HistoryService, 'isUndoDisabled').and.returnValue(false);