如何检查注入控制器中的功能

how to check a function in an injected controller?

本文关键字:控制器 功能 注入 何检查 检查      更新时间:2023-09-26

我目前正试图测试是否调用了控制器上的getTodaysHours函数。最终,函数应该从mock JSON数据中获得小时,并在参数匹配的情况下通过,但我仍停留在第一部分。

供应商控制

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

当我用$provide常量模拟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对于每个@/Users/adminuser/Documents/workspace/thcmaps-ui/bower_components/angular/angular.js:341:24loadModules@/Users/adminuser/Documents/workspace/thcmaps-ui/bower_components/angular/angular.js:4456:12createInjector@/Users/adminuser/Documents/workspace/thcmaps-ui/bower_components/angular/angular.js:4381:22workFn@/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对于每个@/Users/adminuser/Documents/workspace/thcmaps-ui/bower_components/angular/angular.js:341:24loadModules@/Users/adminuser/Documents/workspace/thcmaps-ui/bower_components/angular/angular.js:4456:12createInjector@/Users/adminuser/Documents/workspace/thcmaps-ui/bower_components/angular/angular.js:4381:22workFn@/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:53TypeError: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:2244419

使用$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")所依赖的预期依赖项的对象。

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


  • $controller:https://docs.angularjs.org/guide/unit-testing
  • this:http://jasmine.github.io/2.0/introduction.html

对于Jasmine文档中关于this在测试中的使用的无效链接,我深表歉意,由于锚定标签的设置方式,我无法添加到页面正确部分的直接链接(锚定标签包含<code></code>块,doh!)。