vendredi 20 octobre 2017

Unit testing angularJS controller where data is updated using angular.copy from a factory after a GET call

I'm really new to Angular Unit testing using Karma and Jasmine, and I'm unable to find anything that would guide me in the right direction with regards to my problem. I have my Angular app called myApp. The app has multiple components each defined as their own modules that are then injected in the app.

App

angular.module('myApp', ['ngRoute', 'ui-bootstrap', 'dashboard', 'projects']);

Controller

angular.module('dashboard', []).controller('dashboardController', 
['dashboardService', '$rootScope', '$scope', '$http', function() {

  $scope.teamMemebrs = dashboardService.teamMembers;
  dashboardService.getTeamMemebrs();

}]);

Service

angular.module('dashboard').service('dashboardService',
['$http', '$q', function($http, $q) {
    let loadTeamMembers = () => {
       return $http.get(APIendPoint).then( (response) => {
         return response;
       }, (response) => {
         return response;
       } ); 
    };

    let dashboardService = {
      teamMembers : [],
      getTeamMembers() {
        return $q.when(loadTeamMembers()).then( (response) => {
          let team = response.status === 200 ? response.data : [];
          angular.copy(team, dashboardService.teamMemebrs);
        });
      }          
    };
    return dashboardService;
  }
]);

I am trying to test the controller and my test looks as follows, but the test fails because scope.teamMembers is undefined. What am I doing wrong?

Test Spec

describe('Dashboard', () => {

    let scope, dashboardController, dashboardService, $httpBackend;

    //This is what API call is expected to return
    let sampleResponse = [ {name: 'Jane Doe'},
                           {name: 'Amy Smith'},
                           {name: 'John Hopkins'} ];

    beforeEach(angular.mock.module('myApp'));
    beforeEach(angular.mock.module('dashboard'));

    beforeEach(angular.mock.inject( (_$rootScope_, _$controller_, _dashboardService_, _$httpBackend_) => {

        scope = _$rootScope_.$new();
        $controller = _$controller_;
        dashboardService = _dashboardService_;

        spyOn(dashboardService, 'getTeamMembers').and.callThrough();

        dashboardController = $controller('dashboardController', { $scope: scope, dashboardService: dashboardService });

        scope.$apply();
    }));

    it('should exist', () => {
        expect(dashboardController).toBeDefined();
    });

    it('call dashboardService and populate scope.teamMembers', () => {
        expect(dashboardService.getTeamMembers).toHaveBeenCalled();
        expect(scope.teamMemebrs).toEqual(sampleResponse);
    });
});

Aucun commentaire:

Enregistrer un commentaire