我正在使用 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 。
最佳答案
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/