我有一个 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/