简体   繁体   English

AngularJS&Jasmine:测试是否在范围内调用了一个方法

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

I have this code in a directive 我在指令中有此代码

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" });
                    }
   ...
}

I want to test whether scope.setCurrentBoundary is called, so I wrote this test 我想测试是否scope.setCurrentBoundary ,所以我写了这个测试

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

Problem is that this gives me this error 问题是这给了我这个错误

Error: Expected a spy, but got undefined.

I understand why this is happening but I don't know what the proper way is to test that the particular if statement in my code is being executed and that then the scope.setCurrentBoundary method is being called with those particular arguments. 我知道为什么会这样,但是我不知道测试我代码中特定的if语句是否正在执行,然后使用这些特定参数调用scope.setCurrentBoundary方法的scope.setCurrentBoundary方法是什么。 What is the right way to do that? 什么是正确的方法?

You haven't configured the spy. 您尚未配置间谍。

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

or if you're on jasmine 2.0 或者如果您使用的是茉莉花2.0

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

This must be done before you try to do expectations on the spy (and obviously after the controller is initialized), I prefer doing this in a beforeEach block. 必须在尝试对间谍进行期望之前(显然是在初始化控制器之后)执行此操作,我更喜欢在beforeEach块中执行此beforeEach

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM