AngularJS,Jasmine:测试是否调用了作用域上的方法

AngularJS & Jasmine: Testing that a method on the scope was called

本文关键字:作用域 方法 调用 是否 Jasmine 测试 AngularJS      更新时间:2023-09-26

我在指令

中有这个代码
function createChartOptions(chartData, panelIndex, legendHeights) {
                    if (some condition) {
                        scope.setCurrentBoundary({ min: chartOptions.xAxis[0].min, max: chartOptions.xAxis[0].max, isDatetimeAxis: chartOptions.xAxis[0].type === "datetime" });
                    }
   ...
}

我想测试scope.setCurrentBoundary是否被调用,所以我写了这个测试

it('Should set current boundary', function () {
                expect(scope.setCurrentBoundary).toHaveBeenCalledWith({ min: 1380589200000, max: 1398733200000, isDatetimeAxis: true });
            });

问题是这给了我这个错误

Error: Expected a spy, but got undefined.

我明白为什么会发生这种情况,但我不知道正确的方法是测试我的代码中特定的if语句正在执行,然后scope.setCurrentBoundary方法正在使用这些特定的参数调用。正确的做法是什么?

您还没有配置间谍。

spyOn(scope, 'setCurrentBoundary').andCallThrough();

或者如果你使用的是jasmine 2.0

spyOn(scope, 'setCurrentBoundary').and.callThrough();

这必须在您尝试对spy进行期望之前完成(显然在控制器初始化之后),我更喜欢在beforeEach块中执行此操作。