I'm currently facing a challenge with unit testing my Angular service using the async/await
keywords in the respective (Jasmine) unit tests below. The test for the built-in Promise
is functioning correctly, however, I am encountering difficulties in getting the Angular $q
counterpart to work.
- Angular: 1.6.5
- Jasmine: 2.7.0
- (Headless) Chrome on 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, as well. Why isn't it working?', async (done) => {
const xPromise = xService.getXAfter1SecWithAngular$Q();
$timeout.flush();
const x = await xPromise;
expect(x).toEqual(43);
done();
});
});
Fiddle link provided here: https://jsfiddle.net/glenn/gaoh6bvc/
I've attempted to search on Google for solutions, but unfortunately, I haven't found a clear resolution yet 😞