请参阅此 plunkr 的实例:http://plnkr.co/edit/djQPW7g4HIuxDIm4K8RC
在下面的代码中,行 var Promise = serviceThatReturnsPromise();
在模块配置期间运行,但我想模拟服务返回的 Promise。
理想情况下,我会使用 $q
服务来创建模拟 Promise,但我不能这样做,因为 serviceThatReturnsPromise()
是在模块配置期间执行的,在我可以访问 $q
之前。解决先有鸡还是先有蛋的问题的最佳方法是什么?
var app = angular.module('plunker', []);
app.factory('serviceUnderTest', function (serviceThatReturnsPromise) {
// We mock out serviceThatReturnsPromise in the test
var promise = serviceThatReturnsPromise();
return function() {
return 4;
};
});
describe('Mocking a promise', function() {
var deferredForMock, service;
beforeEach(module('plunker'));
beforeEach(module(function($provide) {
$provide.factory('serviceThatReturnsPromise', function() {
return function() {
// deferredForMock will be undefined because this is called
// when `serviceUnderTest` is $invoked (i.e. at module configuration),
// but we don't define deferredForMock until the inject() below because
// we need the $q service to create it. How to solve this chicken and
// egg problem?
return deferredForMock.promise;
}
});
}));
beforeEach(inject(function($q, serviceUnderTest) {
service = serviceUnderTest;
deferredForMock = $q.defer();
}));
it('This test won\'t even run', function() {
// we won't even get here because the serviceUnderTest
// service will fail during module configuration
expect(service()).toBe(4);
});
});
最佳答案
我不确定我是否喜欢这个解决方案,但它是:
http://plnkr.co/edit/uBwsJxJRjS1qqsKIx5j7?p=preview
您需要确保在设置完所有内容之后才实例化“serviceUnderTest”。因此,我将第二个 beforeEach
分成两个单独的部分:第一个实例化并使用 $q
,第二个实例化并使用 serviceUnderTest
。
我还必须包含 $rootScope
,因为 Angular 的 Promise 被设计为在 $apply()
方法中工作。
希望有帮助。
关于AngularJS:如何在模块配置期间使用 angular.service ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15283423/