I have previously successfully tested an angular controller that uses ES7 async/await syntax with jasmine -
async updateGridAsync() {
const paging = angular.copy(this.gridData.getServerCallObj());
}
try {
const model = await this.service.getAsync(paging);
this._$rootScope.$apply();
} catch (e){this._notification.error(this._$rootScope.lang.notifications.unexpectedError);
}
}
it('updateGridAsync() should update the gridData when succeed', async (done) => {
expect(ctrl.gridData.totalItems).toEqual(2);
expect(ctrl.gridData.items.length).toEqual(2);
spyOn(service, 'getAsync').and.callFake(() => {
return Promise.resolve(responseStub);
});
await ctrl.updateGridAsync();
expect(service.getAsync).toHaveBeenCalled();
expect(ctrl.gridData.totalItems).toEqual(1);
expect(ctrl.gridData.items.length).toEqual(1);
done();
});
The above code works perfectly. However, I encountered a problem once trying to test the mocked service code, that calls $http.post. This is the code I run in the service:
async getAsync(pagingData, spinner, gridId, payeeId){
const response = await $http.post(url, params);
const model = this.modelFactory(response.data);
return model ;
}
and the test method that isn't able to go a step after the await in updateGridService:
it('getAsync should return correct model', async (done) => {
$httpBackend.whenPOST(theUrl).respond(200, responseStub);
const model = await service.getAsync();
expect(model.list.length).toEqual(2);
$httpBackend.flush();
done();
});
A few things to point out -
- Before using async await, this test passed. Now, I don't get passed the await in the service.
- The functionality works when not in testing context.
- I'm using jasmine 2.4.1 and angularJS 1.6