Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 346
Saurabh Kumar Avatar asked Dec 19 '22 11:12

Saurabh Kumar


1 Answers

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

like image 102
m.brand Avatar answered May 12 '23 01:05

m.brand