使用$ q.all进行角度js工厂服务的Jasmine单元测试

时间:2015-10-13 09:31:14

标签: javascript angularjs unit-testing jasmine angular-mock

以下是使用$ resource

从web api获取值的服务
(function () {
'use strict';
function a($resource) {
    return $resource('api/values/a');
}

angular
    .module('app')
    .factory('a', ['$resource', a]);}());

我有一个服务列表,如上述服务

下面是使用上述服务获取值的服务,它将作为单个结果返回 如何使用茉莉花单元测试来测试以下服务我需要以下服务的代码覆盖

(function () {
'use strict';

function factoryService($q, a, b, c, d) {
    function fetch(id) {

        var data = {},
            promises = [];



        data.avalues = a.query();
        promises.push(data.avalues.$promise);

         data.bvalues = b.query();
        promises.push(data.bvalues.$promise);

        data.cvalues = c.query();
        promises.push(data.cvalues.$promise);

        data.dvalues = d.query();
        promises.push(data.dvalues.$promise);

        return $q.all(promises).then(function () {

            return data;
        });
    }

    return {
        fetch: fetch
    };
}

angular
    .module('app')
    .factory('factoryService', ['$q', 'a', 'b', 'c', 'd', factoryService]);}());

任何人都可以帮助我为代码覆盖率的上述工厂服务编写单元测试

描述('从服务中获取a,b,c,d值',function(){

  var service,result,httpBackend,rootScope,$q,scope;

  beforeEach(module('app'));

  beforeEach(inject(function(proposalPlanInitialData, _$httpBackend_,$rootScope, _$q_) {
    $q = _$q_;
    service = proposalPlanInitialData;
    httpBackend = _$httpBackend_;
    rootScope = $rootScope;
    scope = $rootScope.$new();
    deferred = _$q_.defer();
  }));


  it ('should be loaded', function() {
      expect(service).toBeDefined();
  });

  it ('should return get data when calling fetch', function() {
    fakeListing = {
    id: 123,
    price: 300000
    };
     var getData = { "id": '1', "name": "dummyvalue" };
    httpBackend.expectGET('api/values/a').respond({ "id": '1', "name": "dummyvalue" });
    httpBackend.expectGET('api/values/b').respond({ "id": '1', "name": "dummyvalue" });
    httpBackend.expectGET('api/values/c').respond({ "id": '1', "name": "dummyvalue" });
    httpBackend.expectGET('api/values/d').respond({ "id": '1', "name": "dummyvalue" });



    var data = service.fetch(1,1);

    spyOn(service, 'fetch').and.callFake(function () {
    return fakeListing;
    });        
    // httpBackend.flush();
    var data = service.fetch(1);
    expect(data).toBe(fakeListing);});});

但获取未定义的数据

0 个答案:

没有答案