[英]Why does injecting 'ng' in unit tests change promise handling behaviour?
The following service uses $q.when
to wrap a third-party promise: 以下服务在包装第三方诺言时使用
$q.when
:
// service.js
angular.module('test', [])
.service('pouchdb', function($q, $window) {
var db = new $window.PouchDB('test');
this.info = function() {
return $q.when(db.info.apply(db, arguments));
};
});
Corresponding unit test: 对应的单元测试:
describe('Failing Q when tests', function() {
beforeEach(module('test'));
var $rootScope, pouchdb;
beforeEach(inject(function(_$rootScope_, pouchdb) {
$rootScope = _$rootScope_;
pouchdb = pouchdb;
}));
it('should resolve a promise', function(done) {
// FIXME: never resolves
pouchdb.info()
.then(function(info) {
expect(info).toBeDefined();
})
.finally(done);
$rootScope.$apply();
});
});
pouchdb.info
never resolves and Jasmine times out. pouchdb.info
永远不会解决,Jasmine超时。 However, if I manually inject ng
, the spec works as expected: 但是,如果我手动注入
ng
,那么规范将按预期工作:
describe('Working Q when tests', function() {
var pouchdb;
beforeEach(function() {
var $injector = angular.injector(['ng', 'test']);
var pouchDB = $injector.get('pouchdb');
pouchdb = pouchDB('db');
});
it('should resolve a promise', function(done) {
pouchdb.info()
.then(function(info) {
expect(info).toBeDefined();
})
.finally(done);
});
});
Could anyone explain why; 谁能解释为什么?
ng
) ng
) $rootScope.$apply
$rootScope.$apply
Are you using angular-mocks? 您是否正在使用角-? https://docs.angularjs.org/api/ngMock
https://docs.angularjs.org/api/ngMock
The only reason why I think that you'd need to inject 'ng' manually is if there is no ng-app initializing your app, at least according to https://docs.angularjs.org/api/ng/function/angular.module 我认为您需要手动注入ng的唯一原因是,如果没有ng-app初始化您的应用程序,至少根据https://docs.angularjs.org/api/ng/function/angular 。模块
If you use angular-mocks it takes care of that for you https://github.com/angular/angular.js/blob/master/src/ngMock/angular-mocks.js#L1785 如果您使用angular-mocks,它会为您解决这一问题https://github.com/angular/angular.js/blob/master/src/ngMock/angular-mocks.js#L1785
Can't think of any other reason as to why this problem would occur. 想不到为什么会出现此问题的任何其他原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.