Jasmine测试:预期未定义为等于Object

时间:2017-03-12 14:14:10

标签: javascript angularjs jasmine

我是AngularJS的新手。我创建了以下包含模板和关联控制器的组件。

angular.
module('beerDetail').
controller('BeerDetailController',  ['BeerSelection', '$scope', '$rootScope',
  function BeerDetailController(BeerSelection, $scope, $rootScope) {

    let beerSelected = BeerSelection.getBeerSelected();

    $scope.ok = () => { $rootScope.modalInstance.close() };
    $scope.beer = beerSelected;
    $scope.foodPairings = beerSelected.food_pairing.join(", ");

    this.getFormattedIngredients = (ingredients) => {...};

    this.getFormattedMethod = (method) => {...};

    $scope.allIngredients = this.getFormattedIngredients(beerSelected.ingredients);
    $scope.method = this.getFormattedMethod(beerSelected.method);
  }
]).
component('beerDetail', {
  templateUrl: '/components/beer-detail/beer-detail.template.html',
  controller: 'BeerDetailController',
});

我想测试控制器,我创建了以下测试,检查传入范围的啤酒是否是通过调用提供的啤酒:BeerSelection.getBeerSelected()

describe('BeerDetailController', function() {

  it('returns the selected beer', function() {

      beforeEach(module('beerDetail'));

      let $controller;
      let scope;
      let rootScope;
      let createController;
      let beerSelection;
      let beerSelected = {
        "id": 192,
        "name": "Punk IPA 2007 - 2010",
      };

    beforeEach(inject(function ($rootScope, $controller) {
        scope = $rootScope.$new();
        createController = function () {
          return $controller('BeerDetailController',
            {'BeerSelection': beerSelection},
            {'$scope': scope},
            {'$rootScope': rootScope}
            );
          spyOn(beerSelection, 'getBeerSelected').and.returnValues(beerSelected);
        };
    }));

    expect(scope.beer).toEqual(beerSelected);
    });
  });

但我确实收到以下错误:

  

预期未定义为等于对象({id:192,名称:' Punk IPA 2007 -   2010' })

有谁知道问题出在哪里?提前谢谢!

1 个答案:

答案 0 :(得分:2)

您必须调用createController方法来实际创建它。刚刚完成了你在之前的任务中所做的任务。

createController();     
expect(scope.beer).toEqual(beerSelected);

应该正常工作

注册(从评论中编辑):

angular.
module('beerDetail').
controller('BeerDetailController',  {your controller function}).
component('beerDetail', {
  templateUrl: '/components/beer-detail/beer-detail.template.html',
  controller: 'BeerDetailController'
....

我认为这样可行