简体   繁体   English

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

[英]Testing angular service that is also a promise

I'm working with browserify to bundle up an angular service. 我正在使用browserify捆绑一个角度服务。 I'm using jasmine to write tests for this service, which is defined like: 我正在使用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)
}

The following test suite: 以下测试套件:

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

Throws a TypeError: undefined is not a constructor on (evaluating Object.assign(apiRootPromise, otherService)') . 引发TypeError: undefined is not a constructor (evaluating Object.assign(apiRootPromise, otherService)') I'm not sure what's happening here, but my best guess is Angular is not injecting properly the dependent service or not returning the $http promise. 我不确定这里发生了什么,但我最好的猜测是Angular没有正确地注入依赖服务或者没有返回$http承诺。

Possible duplicate question 可能重复的问题

Object.assign is introduced in ECMAScript 6th edition and is not currently natively supported in all browsers. Object.assign在ECMAScript第6版中引入,目前在所有浏览器中都不受支持。 Try using a polyfill for Object.assign . 尝试将polyfill用于Object.assign Here's one: 这是一个:

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

Otherwise, your code is working in this fiddle (I had to fill in a few blanks, but the general gist is there) 否则,你的代码正在这个小提琴中工作 (我必须填写一些空白,但一般的要点就在那里)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM