2017-08-10 67 views
1

我以前成功地測試了使用異步ES7/AWAIT語法與茉莉角控制器 -

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(); 
}); 

上面的代碼完美地工作。但是,一旦嘗試測試調用$ http.post的模擬服務代碼時,我遇到了一個問題。這是我在服務運行代碼:

async getAsync(pagingData, spinner, gridId, payeeId){    
     const response = await $http.post(url, params); 
     const model = this.modelFactory(response.data); 
     return model ; 
    } 

和測試方法,是不是能夠在updateGridService的AWAIT後走了一步:

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(); 
}); 

有幾件事情要指出 -

  • 在使用異步等待之前,通過了該測試。現在,我不會在服務中等待。
  • 當不在測試環境中時,該功能起作用。
  • 我使用茉莉2.4.1和1.6 angularJS
+0

您是否發現任何通過異步通過測試的解決方案? – Nader

回答

0

我不認爲你可以使用那些一起 - 等待實際上是等到後端承諾解決和通過沖洗觸發,也觸發它在任何請求發出之前都沒有好處。