使用 jasmin 使用 $httpBackend 和 async/await 测试角度服务

Rot*_*m B 5 jasmine angularjs ecmascript-2017

我之前已经成功测试了一个使用 ES7 async/await 语法和 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();
});
Run Code Online (Sandbox Code Playgroud)

上面的代码完美运行。然而,当我尝试测试调用 $http.post 的模拟服务代码时遇到了一个问题。这是我在服务中运行的代码:

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

以及 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();
});
Run Code Online (Sandbox Code Playgroud)

有几点需要指出——

  • 在使用asyncawait之前,这个测试通过了。现在,我没有通过服务中的等待。
  • 该功能在不在测试环境中时有效。
  • 我正在使用 jasmine 2.4.1 和 angularJS 1.6

miz*_*shu 2

我不认为你可以一起使用它们——await实际上是在等待后端承诺解决,并且是由flush触发的,但在发出任何请求之前触发它也没有什么好处。

我的意思是,如果您想以简单的方式使用它,我个人将它与一个帮助程序一起使用,该帮助程序为刷新操作创建超时,然后等待请求。

export async function withHttp(
    callbackHttp: (http: HttpTestingController) => void,
    callbackTest: () => Promise<void>
): Promise<void> {
    const http = TestBed.get(HttpTestingController);
    setTimeout(() => callbackHttp(http));
    await callbackTest();
}

Run Code Online (Sandbox Code Playgroud)

也不要将异步测试方法与done一起使用(并且当它只是在测试的最后一行调用时不要使用done,那么就不需要)。