【问题标题】:Testing angular service that is also a promise测试角度服务也是一个承诺
【发布时间】:2016-02-27 12:02:22
【问题描述】:

我正在与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()
    }))
  })

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

【问题讨论】:

    标签: angularjs node.js jasmine browserify


    【解决方案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(我不得不填写一些空白,但大致的要点在那里)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-27
      • 2015-03-22
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      相关资源
      最近更新 更多