我想單元測試我的角度服務使用async/await
關鍵字在相應的(茉莉花)單元測試下面。原生Promise
的測試工作得很好,但我幾乎堅持讓角色$q
對應的工作。使用異步/等待與茉莉花的角度1.x單元測試
- 角:1.6.5
- 茉莉花:2.7.0
- (無頭)鍍在MacOS:60.X
angular
.module('asyncAwaitTest', [])
.factory('xService', xServiceFactory);
function xServiceFactory(
$q,
$timeout
) {
return {
getXAfter1Sec() {
return new Promise(resolve => setTimeout(() => resolve(43), 1000));
},
getXAfter1SecWithAngular$Q() {
const deferred = $q.defer();
$timeout(() => deferred.resolve(43), 1000);
return deferred.promise;
}
};
}
jasmine.DEFAULT_TIMEOUT_INTERVAL = 2000;
describe('asyncAwaitTest: x service',() => {
let $timeout;
let xService;
beforeEach(() => {
module('asyncAwaitTest');
inject(
(
_$timeout_,
_xService_
) => {
$timeout = _$timeout_;
xService = _xService_;
}
);
});
it('should work', async (done) => {
const x = await xService.getXAfter1Sec();
expect(x).toEqual(43);
done();
});
it('should work, too. but y not?!!', async (done) => {
const xPromise = xService.getXAfter1SecWithAngular$Q();
$timeout.flush();
const x = await xPromise;
expect(x).toEqual(43);
done();
});
});
小提琴這裏提供:https://jsfiddle.net/glenn/gaoh6bvc/
我試過谷歌,但它並沒有給我一個信號虛擬良導致
'async/await'不知道'$ q'。他們與本土承諾一起工作。檢查了這一點:https://stackoverflow.com/questions/35629246/typescript-async-await-and-angular-q-service –
我明白了。但有沒有解決方法?把'.run(function runBlock($ window,$ q){$ window.Promise = $ q;});'只會讓情況變得更糟 - 兩次測試都失敗:/ –