Jasmine Test: How to mock a method inside a controller in AngularJS

12,125

Your methods should be in the $scope. It should somehow look like this:

In your Controller:

...
$scope.methodToTest = function () {
    ...
    $scope.methodToMock();
    ...
}
$scope.methodToMock = function () {
    // do something
}
...

In your test:

...
describe( 'methodToTest', function ()
{
    it( 'should call the methodToMock', function() {
        spyOn( $scope, 'methodToMock' );
        $scope.methodToTest();
        expect( $scope.methodToMock ).toHaveBeenCalled();
    } );
} );
...

Maybe this can help you too: http://www.benlesh.com/2013/05/angularjs-unit-testing-controllers.html

Share:
12,125
Saurabh Kumar
Author by

Saurabh Kumar

Updated on June 23, 2022

Comments

  • Saurabh Kumar
    Saurabh Kumar about 2 years

    I am using angularjs and my controller looks like this:

    (function (app) {
    
    var myController = function ($scope, myService) {
    
        var onData = function (response) {
    
            if (!response.data || response.data.length === 0) {
    
                app.showErrorMessage('Error');
    
            } else {
                $scope.myData = response.data;
    
                drawChart();
            }
    
            $scope.loading = false;
        };
    
        var init = function () {
            $scope.loading = true;
            myService.getContBreakdown().then(onData, onError);
        };
    
    
        var drawChart = function () {
        // Some Code
    
        };
    
        init();
    };
    
      app.controller('myController', ['$scope', 'myService', myController]);
    }(angular.module('app')));
    

    I am writing a jasmine test suit to test the data received from the myService, and mock the call to drawChart() method. How should I write the a simple jasmine test suit to mock the call to the drawChart() method?