2016-02-27 44 views
3

我正在与browserify捆绑角度服务。我使用jasmine撰写对这一服务,该服务等被定义测试:测试角度服务也是一个承诺

angular 
    .module('Client', []) 
    .factory('client', ['url', 'otherService', '$http', '$log', client]) 

function client (url, otherService, $http, $log) { 
    $log.debug('Creating for url %s', url) 
    var apiRootPromise = $http.get(url).then(function (apiRoot) { 
    $log.debug('Got api root %j', apiRoot) 
    return otherService.stuff(apiRoot.data) 
    }) 
    return Object.assign(apiRootPromise, otherService) 
} 

下面的测试套件:

describe('test client', function() { 
    beforeEach(function() { 
     angular.mock.module('Client') 
     angular.mock.module(function ($provide) { 
     $provide.value('url', 'http://localhost:8080/') 
     }) 
    }) 

    it('should connect at startup', angular.mock.inject(function (client, $rootScope, $httpBackend) { 
     $rootScope.$apply() 
     $httpBackend.flush() 
     expect(client).toBeDefined() 
    })) 
    }) 

抛出TypeError: undefined is not a constructor(evaluating Object.assign(apiRootPromise, otherService)')。我不确定这里发生了什么,但我最好的猜测是Angular没有正确注入依赖服务或者没有返回$http的承诺。

回答

1

Possible duplicate question

Object.assign ECMAScript的第6版介绍,目前并未在所有浏览器原生支持。尝试使用Object.assign的polyfill。这里有一个:

if (typeof Object.assign != 'function') { 
    (function() { 
    Object.assign = function (target) { 
     'use strict'; 
     if (target === undefined || target === null) { 
     throw new TypeError('Cannot convert undefined or null to object'); 
     } 

     var output = Object(target); 
     for (var index = 1; index < arguments.length; index++) { 
     var source = arguments[index]; 
     if (source !== undefined && source !== null) { 
      for (var nextKey in source) { 
      if (source.hasOwnProperty(nextKey)) { 
       output[nextKey] = source[nextKey]; 
      } 
      } 
     } 
     } 
     return output; 
    }; 
    })(); 
} 

否则,你的代码是working in this fiddle(我不得不填补一些空白,但总的要点是有)