42

我有一个 ParseService,我想模拟它以测试所有使用它的控制器,我一直在阅读有关 jasmine 间谍的信息,但我仍然不清楚。谁能给我一个如何模拟自定义服务并在控制器测试中使用它的示例?

现在我有一个控制器,它使用服务插入一本书:

BookCrossingApp.controller('AddBookCtrl', function ($scope, DataService, $location) {

    $scope.registerNewBook = function (book) {
        DataService.registerBook(book, function (isResult, result) {

            $scope.$apply(function () {
                $scope.registerResult = isResult ? "Success" : result;
            });
            if (isResult) {
                //$scope.registerResult = "Success";
                $location.path('/main');
            }
            else {
                $scope.registerResult = "Fail!";
                //$location.path('/');
            }

        });
    };
});

服务是这样的:

angular.module('DataServices', [])

    /**
     * Parse Service
     * Use Parse.com as a back-end for the application.
     */
    .factory('ParseService', function () {
        var ParseService = {
            name: "Parse",

            registerBook: function registerBook(bookk, callback) {

                var book = new Book();

                book.set("title", bookk.title);
                book.set("description", bookk.Description);
                book.set("registrationId", bookk.RegistrationId);
                var newAcl = new Parse.ACL(Parse.User.current());
                newAcl.setPublicReadAccess(true);
                book.setACL(newAcl);

                book.save(null, {
                    success: function (book) {
                        // The object was saved successfully.
                        callback(true, null);
                    },
                    error: function (book, error) {
                        // The save failed.
                        // error is a Parse.Error with an error code and description.
                        callback(false, error);
                    }
                });
            }
        };

        return ParseService;
    });

到目前为止,我的测试如下所示:

describe('Controller: AddBookCtrl', function() {

    //  // load the controller's module
    beforeEach(module('BookCrossingApp'));


    var AddBookCtrl, scope, book;

    // Initialize the controller and a mock scope
    beforeEach(inject(function($controller, $rootScope) {
        scope = $rootScope;
        book = {title: "fooTitle13"};
        AddBookCtrl = $controller('AddBookCtrl', {
            $scope: scope
        });
    }));

    it('should call Parse Service method', function () {

        //We need to get the injector from angular
        var $injector = angular.injector([ 'DataServices' ]);
        //We get the service from the injector that we have called
        var mockService = $injector.get( 'ParseService' );
        mockService.registerBook = jasmine.createSpy("registerBook");
        scope.registerNewBook(book);
        //With this call we SPY the method registerBook of our mockservice
        //we have to make sure that the register book have been called after the call of our Controller
        expect(mockService.registerBook).toHaveBeenCalled();
    });
    it('Dummy test', function () {
        expect(true).toBe(true);
    });
});

现在测试失败了:

   Expected spy registerBook to have been called.
   Error: Expected spy registerBook to have been called.

我做错了什么?

4

4 回答 4

60

我做错的是没有将模拟服务注入到 beforeEach 中的控制器中:

describe('Controller: AddBookCtrl', function() {

    var scope;
    var ParseServiceMock;
    var AddBookCtrl;

    // load the controller's module
    beforeEach(module('BookCrossingApp'));

    // define the mock Parse service
    beforeEach(function() {
        ParseServiceMock = {
            registerBook: function(book) {},
            getBookRegistrationId: function() {}
       };
   });

   // inject the required services and instantiate the controller
   beforeEach(inject(function($rootScope, $controller) {
       scope = $rootScope.$new();
       AddBookCtrl = $controller('AddBookCtrl', {
           $scope: scope,
           DataService: ParseServiceMock
       });
   }));

   it('should call registerBook Parse Service method', function () {
       var book = {title: "fooTitle"}

       spyOn(ParseServiceMock, 'registerBook').andCallThrough();
       //spyOn(ParseServiceMock, 'getBookRegistrationId').andCallThrough();
       scope.registerNewBook(book);

       expect(ParseServiceMock.registerBook).toHaveBeenCalled();
       //expect(ParseServiceMock.getBookRegistrationId).toHaveBeenCalled();
    });
});
于 2013-04-09T21:59:05.770 回答
11

您可以注入您的服务,然后像这样使用 spyOn.and.returnValue() :

beforeEach(angular.mock.module('yourModule'));

beforeEach(angular.mock.inject(function($rootScope, $controller, ParseService) {
    mock = {
        $scope: $rootScope.$new(),
        ParseService: ParseService
    };
    $controller('AddBookCtrl', mock);
}));

it('should call Parse Service method', function () {
    spyOn(mock.ParseService, "registerBook").and.returnValue({id: 3});

    mock.$scope.registerNewBook();

    expect(mock.ParseService.registerBook).toHaveBeenCalled();
});
于 2014-07-03T12:43:29.017 回答
2

事后 4 年遵循 Javito 的回答。Jasmine 在 2.0 中更改了它们的语法,用于调用间谍的真实方法。

改变:

spyOn(ParseServiceMock, 'registerBook').andCallThrough();

到:

spyOn(ParseServiceMock, 'registerBook').and.callThrough();

来源

于 2017-09-24T16:21:44.847 回答
-2

在您的项目中包含angular-mocks.js并通过以下链接仔细阅读。

于 2013-04-07T06:55:34.070 回答