如何对另一个函数进行单元测试

时间:2016-11-05 16:55:26

标签: angularjs unit-testing jasmine

对于单元测试,我使用jasmine。我想测试filterList函数。 我怎么能这样做?问题是我模拟了服务对象,但是如何在mock对象中声明方法以便我可以测试filterList函数。

忽略语法,因为我复制粘贴代码并删除一些行,因此很有可能存在很多语法错误。

function (_,angular) {
    'use strict';
    var ngDependencies = ['StateService','$scope','$rootScope'];
    var Constructor = function Constructor(StateService,$scope,$rootScope) {
        var self = this;
        self.defaultSelectedCompany = {};

        self.companies = {
            available: []
        };

        var ChangeListener = StateService.subscribe(function () {
            self.companies.available = StateService.getAvailable('clients');

            self.myCompanyList = _.map(self.companies.available, function companyList(user) {
                return {
                    id: user.name};
            });

    self.filterList = function filterList($searchVal, $list) {
            return _.filter($list, function (item) {
                return item.displayValue.toLowerCase().indexOf($searchVal.toLowerCase()) >= 0 ||
                    item.secondaryValue.toLowerCase().indexOf($searchVal.toLowerCase()) >= 0;
            });
        };
            self.updateDefaultCompany(self.myCompanyList[0]);
        });

        self.updateDefaultCompany = function updateDefaultCompanyPreference(selected) {
            self.defaultSelectedCompany = selected;
        };

        $scope.$on('$destroy', ChangeListener);
    };
    Constructor.$inject = ngDependencies;
    return Constructor;

我的spec文件如下:

  function (angular, _) {
    'use strict';
          var MockStateService = {
            name: 'GlobalStateService',
            subscribe: jasmine.createSpy('subscribe').and.callFake(function subscribe(state){
             return {
             filterList : function filterList($searchVal, $list) {
              return _.filter($list, function (item) {
                return item.displayValue.toLowerCase().indexOf($searchVal.toLowerCase()) >= 0 ||
                   item.secondaryValue.toLowerCase().indexOf($searchVal.toLowerCase()) >= 0;
                });
               }
              };
             })
        };
    describe('Controller', function () {
        beforeEach(function () {
            module(Module.name);
            utils.useMocks([
                MockStateService
            ]);
        });
        beforeEach(inject(function ($controller, $rootScope) {
            this.scope = $rootScope.$new();
            this.reqDrawerCtrl = $controller('SettingsController', {$scope: this.scope});
        }));
        describe('filterList', function () {
            it('is a function', function () {
                expect(typeof this.reqDrawerCtrl.filterList).toBe('function');
            });
        });
    });

0 个答案:

没有答案