如何使用ajax服务实现Angular JS控制器的单元测试?

时间:2017-12-14 04:35:02

标签: angularjs ajax unit-testing angular-unit-test

我曾尝试为下面的代码编写单元测试,但我无法实现它。

服务代码:

angular.module('ActivityApp').service('PersonService', [
    '$http',
    function ($http) {

        var person = function () {
            return $http({
                method: 'GET',
                url: '/apis/person'
            });
        };

        return {
            Person: person
        }
    }]);

控制器代码

angular.module('ActivityApp').controller('PersonController', [
    '$scope',
    'PersonService',
    function ($scope, PersonService) {
        'use strict';

        $scope.person = PersonService.Person().then(function(res) { alert(res.data) });


        $scope.save = function () {
            PersonService.Person().then(function (res) { alert(res.data) });
        };
    }]);

单元测试代码:

describe("EDI controller", function () {
    var $httpBackend, $rootScope, mycontroller, personService, $http, $httpBackend, $scope, deferred, $controller;

    beforeEach(module('ediapp'));

    beforeEach(function () {
        filesAjaxService = jasmine.createSpyObj('personService', [
            'Person'
        ]);

        module(function ($provide) {
            $provide.value('personService', personService);
        });
    });

    beforeEach(inject(function (_$controller_, _$rootScope_, _personService_, _$http_, _$httpBackend_) {
        // The injector unwraps the underscores (_) from around the parameter names when matching
        $controller = _$controller_;
        $scope = _$rootScope_.$new();
        $rootScope = _$rootScope_;
        personService = _personService_;
        $http = _$http_;
        $httpBackend = _$httpBackend_;
        mycontroller = $controller("filesCtrl", {
            $scope: $scope,
            PersonService: personService
        });

    }));

    it("Called", function () {
        // expect(fileController).toBeDefined();
        // expect(filesAjaxService.GetAllFiles).toHaveBeenCalled();
    });

    afterEach(function () {
        // $httpBackend.verifyNoOutstandingExpectation();
        // $httpBackend.verifyNoOutstandingRequest();
    });

});

当我运行上面的测试用例时,我得到以下错误

  

TypeError:undefined不是对象(评估   ' PersonService.Person(),然后(&#39)。

任何人都可以提供解决此问题的解决方案吗?

1 个答案:

答案 0 :(得分:0)

这个问题让我很好奇我正在寻找一个解决方案,因为我之前没有这样做过,这对我来说非常好。

  

我像你一样在答案后搜索,我能够将它们合并在一起。

希望帮助你 [你可以在这里测试]



var app = angular.module('app', []);

app.controller('ctrl', function($scope, httpService) {

  $scope.url = "https://jsonplaceholder.typicode.com/users";

  httpService.getUsers().then(function(data) {
    $scope.users = data;
  })

});

app.service("httpService", function($http) {
  this.getUsers = function() {
    return $http.get("https://jsonplaceholder.typicode.com/users")
      .then(function(response) {
        return response.data;
      });
  }

})

describe('unitTest', function() {

  beforeEach(module('app'));

  var $controller, $httpService;

  beforeEach(inject(function($injector, _$controller_, _httpService_) {
    $httpBackend = $injector.get('$httpBackend');
    $controller = _$controller_;
    $httpService = _httpService_;
  }));


  describe('getUsers', function() {
    it('get users from httpService.getUsers()', inject(function() {
      var $scope = {};
      var controller = $controller('ctrl', {
        $scope: $scope
      });

      $httpService.getUsers().then(function(data) {
        $scope.valid = true;
        $scope.response = data;
      })

      $httpBackend.when('GET', $scope.url).respond(200, {
        foo: 'bar'
      });

      $httpBackend.flush();

      expect($scope.valid).toBe(true);
      expect($scope.response).toEqual({
        foo: 'bar'
      });
    }));
  });
});

<!-- Jasmine References -->
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine-html.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/boot.min.js"></script>

<!-- Angular and Angular Mock references -->
<script type="text/javascript" src="https://code.angularjs.org/1.4.0-rc.2/angular.min.js"></script>
<script type="text/javascript" src="https://code.angularjs.org/1.4.0-rc.2/angular-mocks.js"></script>

<div ng-app="app" ng-controller="ctrl">
  <ul>
    <li ng-repeat="user in users">
      {{user.name}}
    </li>
  </ul>
</div>
&#13;
&#13;
&#13;