加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 模拟服务以测试控制器

发布时间:2020-12-17 08:44:31 所属栏目:安全 来源:网络整理
导读:我有一个ParseService,我想嘲笑的顺序测试所有的控制器,使用它,我一直在阅读关于茉莉花间谍,但它仍然不清楚我。任何人都可以给我一个例子,如何模拟自定义服务,并在控制器测试中使用它? 现在我有一个控制器使用服务插入一本书: BookCrossingApp.contr
我有一个ParseService,我想嘲笑的顺序测试所有的控制器,使用它,我一直在阅读关于茉莉花间谍,但它仍然不清楚我。任何人都可以给我一个例子,如何模拟自定义服务,并在控制器测试中使用它?

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

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.

我做错了什么?

我做错了没有注入Mocked服务到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();
    });
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读