简体   繁体   中英

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

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. 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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