测试角度服务也是一种承诺

时间:2016-02-27 12:02:23

标签: angularjs node.js jasmine browserify

我正在使用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 个答案:

答案 0 :(得分:1)

Possible duplicate question

Object.assign在ECMAScript第6版中引入,目前在所有浏览器中都不受支持。尝试将填充物用于Object.assign。这是一个:

    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(我必须填写一些空白,但一般的要点就在那里)