我用$ q包装一个原生的js promise。在测试中本机承诺得到解决,但$ q不是。 我正在使用业力茉莉花
it('promise', () => {
let $q, $rootScope;
inject((_$q_ : any, _$rootScope_ : any, ) => {
$q = _$q_;
$rootScope = _$rootScope_;
});
const deferred = $q.defer();
const promise = new Promise(function (resolve, reject) {
resolve('Stuff worked!');
});
promise.then(function (x) {
console.log('inside then', x); // THIS IS RESOLVING
deferred.resolve(x);
}).catch(function (x) {
deferred.reject(x);
});
deferred.promise.then((x) => {
console.log(x); // THIS IS NEVER RESOLVED
}, (y) => {
console.log(y);
});
$rootScope.$apply();
$rootScope.$digest();
});
我甚至试图将它包装在$ timeout ......
答案 0 :(得分:0)
找到解决方案。使用完成功能
fit('promise', (done) => {
let $q, $rootScope;
inject((_$q_: any, _$rootScope_: any) => {
$q = _$q_;
$rootScope = _$rootScope_;
});
const deferred = $q.defer();
const promise = new Promise(function (resolve, reject) {
resolve('Stuff worked!');
});
deferred.promise.then((x) => {
done(); // THIS WILL CAUSE KARMA T WAIT AND RESOLV THE PROMISE
//expect.......
}, (y) => {
console.log(y);
});
promise.then(function (x) {
console.log('inside then', x);
deferred.resolve(x);
$rootScope.$apply(); //MUST ADD APPLY HERE TOO
}).catch(function (x) {
deferred.reject(x);
});
$rootScope.$apply();
$rootScope.$digest();
});