javascript - Angular 服务在 spyOn 时变得未定义

标签 javascript angularjs jasmine karma-jasmine spyon

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

给出来自 Controller 的代码:

    $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 时,调用 HistoryService.isUndoDisabled() 来自 $scope.isUndoDisabled 返回未定义然后测试失败因为:

Expected spy undoAction not to have been called.

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

最佳答案

spyOn(...)spyOn(...).and.stub() 的快捷方式,而不是 spyOn(...) .and.callThrough()。当以这种方式被监视时,HistoryService.isUndoDisabled() 返回 undefined

测试单元的正确方法是将它与其他单元隔离开来。由于测试的是 Controller ,因此应该模拟或 stub 该服务:

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

然后在另一个测试中:

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

关于javascript - Angular 服务在 spyOn 时变得未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47866124/

相关文章:

javascript - 不能点击div

javascript - Express with ParseServer - 无法连接到 <ip> 端口 1337,连接超时

javascript - 幻灯片中的图像淡入淡出?

javascript - Jasmine .js : Race Conditions when using "runs"

javascript - 为什么文本在使用 toEqual 时不匹配 Angular ?

javascript - IE 中数据属性长度的限制?

javascript - 如何在 ng-repeat 中为变量设置类

javascript - 如何在 Angular js中创建对象名称

javascript - AngularJS:如何在 View 中显示html数据?

unit-testing - 带有 ngrx 的 angular 2 组件 - 运行单元测试时出错