angular-1.x-async-await-jasmine-unit-testing
by Glenn Dwiyatcita
HTML
<link rel="stylesheet" href="https://jasmine.github.io/2.8/lib/jasmine.css">
<script src="https://jasmine.github.io/2.8/lib/jasmine.js"></script>
<script src="https://jasmine.github.io/2.8/lib/jasmine-html.js"></script>
<script src="https://jasmine.github.io/2.8/lib/boot.js"></script>
<script src="//code.angularjs.org/1.6.5/angular.min.js"></script>
<script src="//code.angularjs.org/1.6.5/angular-mocks.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
JavaScript
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();
});
});