模拟服务以测试控制器 [英] Mock a service in order to test a controller

查看:18
本文介绍了模拟服务以测试控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a ParseService, that I would like to mock in order test all the controllers that are using it, I have been reading about jasmine spies but it is still unclear for me. Could anybody give me an example of how to mock a custom service and use it in the Controller test?

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

Right now I have a Controller that uses a Service to insert a book:

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;
    });

到目前为止我的测试是这样的:

And my test so far look like this:

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.

我做错了什么?

推荐答案

我做错的不是在 beforeEach 中将 Mocked Service 注入控制器:

What I was doing wrong is not injecting the Mocked Service into the controller in the 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();
    });
});

这篇关于模拟服务以测试控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆