茉莉花单元测试角度服务

时间:2016-09-06 13:23:22

标签: angularjs jasmine

我开始在单元测试angularjs中使用Jasmine并看到很多示例但不工作我有用户服务,我需要对它进行单元测试 我需要工作演示

(function () {
'use strict';

angular
    .module('app')
    .factory('UserService', UserService);

UserService.$inject = ['$http'];
function UserService($http) {
    var service = {};

    service.GetAll = GetAll;

    return service;

    function GetAll(page) {
      return $http.get('https://api.github.com/users').then(handleSuccess, handleError('Error getting all users'));
    }

    // private functions

    function handleSuccess(res) {
        return res.data;
    }

    function handleError(error) {
        return function () {
            return { success: false, message: error };
        };
    }
}})();

1 个答案:

答案 0 :(得分:3)

以下是您服务的测试演示:

describe("UserService", function() {
  var service;
  var $rootScope;
  var $httpBackend;

  var dataMock = ["John", "Albert", "Mary"];

  beforeEach(module('app'));

  beforeEach(inject(function($injector) {
    $rootScope = $injector.get('$rootScope');
    $httpBackend = $injector.get('$httpBackend');
    service = $injector.get('UserService');
  }));

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

  it('should fetch 3 users', function() {
    $httpBackend.when('GET', 'https://api.github.com/users').respond(dataMock);
    service.GetAll().then(function(users) {
      expect(users.length).toBe(3);
      expect(users).toEqual(dataMock);
    });
    $httpBackend.flush();
  });

  it('should return error', function() {
    $httpBackend.when('GET', 'https://api.github.com/users').respond(403);
    service.GetAll().then(function(error) {
      expect(error.success).toBe(false);
      expect(error.message).toEqual('Error getting all users');
    });
    $httpBackend.flush();
  });
});

你可以看到它在Plunker上工作:https://plnkr.co/edit/agV0rO?p=preview