angularjs - 测试 angular.service 也是一个 promise

标签 angularjs node.js jasmine browserify

我正在使用 browserify 来捆绑 angular.service 。我正在使用 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 没有正确注入(inject)依赖服务或者没有返回 $http promise 。

最佳答案

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

关于angularjs - 测试 angular.service 也是一个 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35669479/

相关文章:

angularjs - 将单个输入元素设置为 ng-pristine

node.js - 将 meteor 与 CoffeeScript 和 Jade 一起使用 : callback[i]. 调用不是函数

node.js如何在中间件中从redis数据库中获取数据

Angular - ReferenceError : Can't find variable: URLSearchParams in http://localhost:9877src/test. ts

selenium - 带 Protractor 的 browserstack 报告

javascript - 无法让 Angular 应用程序在 MVC 布局中工作

javascript - AngularJS : How to execute function in pre-defined order?

javascript - Angular JS。如何禁用自动滚动到我的页面顶部

node.js - 使用 Nodejs 将对话记录到 Azure CosmosDB

javascript - 使用 Jest CLI 时如何让 Promises 工作?