lundi 5 janvier 2015

Why does injecting 'ng' in unit tests change promise handling behaviour?

The following service uses $q.when to wrap a third-party promise:



// 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. However, if I manually inject ng, the spec works as expected:



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;



  1. The first spec doesn't resolve

  2. The second spec does (injecting ng)

  3. It doesn't need $rootScope.$apply

  4. Whether it's a good pattern to use


Aucun commentaire:

Enregistrer un commentaire