2016-09-06 20 views
0

私はユニットテストangularjsにジャスミンを使用し、多くの例を見始めるが、動作しない私はusersserviceを持っていると私はそれ のためのユニットテストを行う必要があり、私は仕事のデモジャスミンユニットテストの角度サービス

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

答えて

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

+1

はい、それは細かいおかげで動作します –