如何检查注入控制器中的函数?

时间:2016-05-03 14:08:52

标签: javascript angularjs json unit-testing jasmine

我目前正在尝试测试我的控制器上是否已调用 getTodaysHours 函数。最终函数应该从模拟JSON 数据获得小时并在参数匹配时传递,但是我被困在第一部分。

vendor.controller

export class VendorController {
    constructor($rootScope, data, event, toastr, moment, _, distanceService, vendorDataService, userDataService, stateManagerService) {
        'ngInject';
        //deps
        this.$rootScope = $rootScope;
        this.toastr = toastr;
        this._ = _;
        this.userDataService = userDataService;
        this.vendorDataService = vendorDataService;
        this.stateManagerService = stateManagerService;
        this.event = event;

        //bootstrap
        data.isDeepLink = true;
        this.data = data;
        this.data.last_update = moment(this.data.updated_at).format('MM/DD/YY h:mm A');
        this.data.distance = distanceService.getDistance(this.data.loc.lng, this.data.loc.lat);
        this.data.todaysHours = this.getTodaysHours();
        this.data.rating_num = Math.floor(data.rating);


        this.hasReviewed = (userDataService.user.reviewed[data._id]) ? true : false;
        this.isGrid = false;
        this.isSearching = false;
        this.hideIntro = true;
        this.menuCollapsed = true;
        this.filterMenuCollapsed = true;

        this.selectedCategory = 'All';
        this.todaysHours = '';
        this.type = '';
        this.searchString = '';

        this.reviewScore = 0;

        this.today = new Date().getDay();

        this.vendorDataService.currentVendor = data;

        //load marker onto map
        $rootScope.$broadcast(event.ui.vendor.pageLoad, data);

        //get menu
        vendorDataService.getVendorMenu(data._id)
            .then((res)=> {
                this.data.menu = res.menu;
                this.menuContainer = this.data.menu;
                this.totalResults = this.getTotalResults();
                this.availableMenuCategories = this.getAvailableMenuCategories();
            })
            .catch(() => {
                this.toastr.error('Whoops, Something went wrong! We were not able to load the menu.',  'Error');
            });
    }

    //get todays hours
    getTodaysHours() {
        let today = this.data.hours[new Date().getDay()];
        return (today.opening_time || '9:00am') + ' - ' + (today.closing_time || '5:00pm');
    }  
}

当我使用 $提供常量

模拟JSON数据时,第一个测试通过
describe('vendor controller', () => {
    let vm,
        data = {"_id":"56b54f9368e685ca04aa0b87","lat_lon":"33.713018,-117.841101","hours":[{"day_of_the_week":"sun","closing_time":" 7:00pm","opening_time":"11:00am","day_order":0,"id":48880},...];

    beforeEach(angular.mock.module('thcmaps-ui', ($provide) => {
        $provide.constant('data', new data);
      }));

    //first test
    it('should pass', () => {
        expect(data._id).toEqual('56b54f9368e685ca04aa0b87');
    });

    //second test
    it('should call getTodaysHours', () => {
    expect(vm.getTodaysHours()).toHaveBeenCalled();
    });
});

然后我尝试注入控制器(不确定语法是否正确):

beforeEach(angular.mock.module('thcmaps-ui', ($provide) => {
    $provide.constant('data', new data);
  }));
beforeEach(inject(($controller) => {
    vm = $controller('VendorController');
    spyOn(vm,'getTodaysHours').and.callThrough();
}));

它给了我某种forEach错误。在评估vm.getTodaysHours()时,第二个测试给出了一个未定义的错误:

  

PhantomJS 2.1.1(Mac OS X 0.0.0)供应商控制器应该通过FAILED       forEach@/Users/adminuser/Documents/workspace/thcmaps-ui/bower_components/angular/angular.js:341:24       loadModules@/Users/adminuser/Documents/workspace/thcmaps-ui/bower_components/angular/angular.js:4456:12       createInjector@/Users/adminuser/Documents/workspace/thcmaps-ui/bower_components/angular/angular.js:4381:22       workFn@/Users/adminuser/Documents/workspace/thcmaps-ui/bower_components/angular-mocks/angular-mocks.js:2507:60       /Users/adminuser/Documents/workspace/thcmaps-ui/bower_components/angular/angular.js:4496:53

     

PhantomJS 2.1.1(Mac OS X 0.0.0)供应商控制器应调用getTodaysHours FAILED       forEach@/Users/adminuser/Documents/workspace/thcmaps-ui/bower_components/angular/angular.js:341:24       loadModules@/Users/adminuser/Documents/workspace/thcmaps-ui/bower_components/angular/angular.js:4456:12       createInjector@/Users/adminuser/Documents/workspace/thcmaps-ui/bower_components/angular/angular.js:4381:22       workFn@/Users/adminuser/Documents/workspace/thcmaps-ui/bower_components/angular-mocks/angular-mocks.js:2507:60       /Users/adminuser/Documents/workspace/thcmaps-ui/bower_components/angular/angular.js:4496:53       TypeError:undefined不是/Users/adminuser/Documents/workspace/thcmaps-ui/.tmp/serve/app/index.module.js中的对象(评估'vm.getTodaysHours')(第9行)       /Users/adminuser/Documents/workspace/thcmaps-ui/.tmp/serve/app/index.module.js:9:244419

1 个答案:

答案 0 :(得分:1)

在使用$controller实例化控制器时,需要注入控制器的依赖项。例如,请考虑以下控制器:

class MyController {
  constructor($rootScope, $log) {
    // Store the controllers dependencies
    this.$rootScope = $rootScope;
    this.$log = $log;
  }

  // Return obituary value from the $rootScope
  getValue() {
    this.$log.debug('Retrieving value');
    return this.$rootScope.foobar;
  }

  // Get the current date
  getDate() {
    this.$log.debug('Getting date');
    return Date.now()
  }

  static get $inject() {
    return ['$scope', '$log'];
  }
}
  

我使用ES6编写了这个控制器,请注意,依赖关系是在类声明脚下的静态$inject getter中定义的。这将由AngularJS在实例化时获取。

如您所见,控制器依赖于$rootScope$log提供程序。在模拟此控制器以进行测试时,必须注入控制器依赖项,如下所示:

describe('Spec: MyController', () => {
  var controller;

  beforeEach(inject(($rootScope, $log, $controller) => {
    controller = $controller('MyController', {
      $rootScope,
      $log
    });
  });

  it('should return a value from the $rootScope', () => {
    var value = controller.getValue();
    // ... perform checks
  });

  it('should return the current date', () => {
    var date = controller.getDate();
    // ... perform checks
  });
});
  

更新版本的Jasmine使开发人员能够在整个测试过程中使用this关键字。

     

所有beforeEachafterEachit声明都会与this共享相同的引用,从而可以避免创建封闭变量(例如var controller ,如上所示)并且还避免创建不必要的全局变量。例如:

beforeEach(inject(function ($rootScope, $log, $controller) {
  this.controller = $controller('MyController', {
    $rootScope,
    $log
  });
});

it('should return a value from the $rootScope', function () {
  this.value = controller.getValue();
  // ... perform checks
});

注意调用$controller中的第二个参数,它必须是一个包含控制器(在本例中为“MyController”)所依赖的预期依赖项的对象。

这背后的原因只是允许开发人员将模拟服务,工厂,提供商等传递给控制器​​,作为间谍的替代方案。

  

对Jasmine文档中关于this与测试的使用的无用链接表示道歉,由于他们的锚标记的设置方式,我无法添加指向页面正确部分的直接链接(锚标记包含<code></code>块,doh!)。