Anto
Anto

Reputation: 4305

Jasmine Testing: Expected undefined to equal Object

I am new to AngularJS. I have created the following component that contains a template and an associated controller.

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

I would like to test the controller, I have created the following test that check whether the beer passed into the scope is the one provided by calling: 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);
    });
  });

I do get the following error however:

Expected undefined to equal Object({ id: 192, name: 'Punk IPA 2007 - 2010' })

What might the problem be?

Upvotes: 1

Views: 9188

Answers (1)

user5741800
user5741800

Reputation:

You have to call the createController method to actually create it. Is just made an assignment youy did in your beforeEach.

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

should be working

To register (edit from comment) :

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

I think this sould work

Upvotes: 2

Related Questions