0

I have the following code in an angularjs controller:

async updateGrid() {
        const paging = angular.copy(this.gridData.getServerCallObj());            
        try {
            const model = await this.service.get(paging);
            this._setGridData(model, true);
            this._$rootScope.$apply();
        } catch (e){
            this._notification.error(this._$rootScope.lang.notifications.unexpectedError);
        }
    }

I am trying to test this code through jasmin. The following test is run:

it('updateGrid() should should call broadcast when fail', async () => {
    spyOn(service, 'get').and.callFake(() => {
        return Promise.reject();
    });
    spyOn($rootScope, '$broadcast').and.callThrough();

    await ctrl.updateGrid();
    expect(service.get).toHaveBeenCalled();
    expect($rootScope.$broadcast).toHaveBeenCalled();
});

My issue is that jasmine return a result for the test with the message "spec... has not expectations." before the function completes! I can continue debugging, after jasmin says the test is done, at his end! Of course, after its done, the line expect(service.get).toHaveBeenCalled(); throws and error with the message: "expect' was used when there was no current spec, this could be because an asynchronous test timed out".

Does anyone knows what am I doing wrong here?

Rotem B
  • 1,327
  • 1
  • 15
  • 20
  • There may be other problems that are related to $q/native promise integration (that's tricky topic), but the main problem here is that it is sync test, there's no `done` function. The latest Jasmine accepts promise returns but not previous versions, the question lacks this info. – Estus Flask Aug 09 '17 at 13:26
  • The [async](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) and [await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) operators are [syntactic sugar](https://en.wikipedia.org/wiki/Syntactic_sugar) that create/resolve ES6 promises. ES6 promises are not integrated with the AngularJS framework and its digest cycle. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc. – georgeawg Aug 09 '17 at 14:32
  • To **convert** ES6 promise to AngularJS promises, use [$q.resolve](https://docs.angularjs.org/api/ng/service/$q#resolve). Avoid ES6 promises when working with AngularJS. It is best to convert any promises from unknown libraries to $q promise as soon as possible. – georgeawg Aug 09 '17 at 14:46
  • @estus your answer gave me everything I need here. Once changing the mock to return Promise.reject and injecting the function with the done operator and calling it after all expectations, everything worked like charm. Thanks! – Rotem B Aug 10 '17 at 04:43

0 Answers0