Jasmine Test:如何在AngularJS中模拟控制器内的方法

Sau*_*mar 4 unit-testing jasmine angularjs

我正在使用angularjs,我的控制器看起来像这样:

(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')));
Run Code Online (Sandbox Code Playgroud)

我正在编写一个jasmine测试套件来测试从myService接收的数据,并模拟对drawChart()方法的调用.我应该如何编写一个简单的茉莉花测试套件来模拟对drawChart()方法的调用?

小智 11

您的方法应该在$ scope中.它应该看起来像这样:

在您的控制器中:

...
$scope.methodToTest = function () {
    ...
    $scope.methodToMock();
    ...
}
$scope.methodToMock = function () {
    // do something
}
...
Run Code Online (Sandbox Code Playgroud)

在你的测试中:

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

也许这也可以帮到你:http: //www.benlesh.com/2013/05/angularjs-unit-testing-controllers.html