单元测试angularJS控制器,其中在GET调用之后使用来自工厂的angular.copy更新数据

时间:2017-10-20 18:10:47

标签: javascript angularjs unit-testing testing karma-jasmine

我使用Karma和Jasmine对Angular Unit测试真的很陌生,而且我无法找到任何可以指导我解决问题的方向。我有一个名为myApp的Angular应用程序。该应用程序有多个组件,每个组件都定义为自己的模块,然后在应用程序中注入。

应用

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

控制器

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

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

}]);

服务

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

我正在尝试测试控制器,我的测试看起来如下,但测试失败,因为scope.teamMembers未定义。我做错了什么?

测试规范

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

0 个答案:

没有答案