包含HTTP订阅的服务方法的测试用例-Angular HTTP RxJs

时间:2019-07-10 11:40:34

标签: angular unit-testing karma-jasmine angular-test httptestingcontroller

我有一个服务方法,它有一个服务调用(HTTP调用),它立即订阅,并根据响应代码执行其余的动作命令。

示例:服务方法

0xBC

我尝试了以下示例(测试用例)

processData(id): void {
    const url = `http://localhost:5000/data/${id}`;

    this.http.head(url).subscribe(() => {
        console.log('Success');

        // Rest of the code - TODO

    }, (error) => {
        console.log('Failed');        

        // Rest of the code - TODO

    });
}

请协助我处理这种情况。

1 个答案:

答案 0 :(得分:1)

您的服务不应订阅可观察到的HttpClient,因此,它不应是无效的返回类型方法。服务应该返回一个可观察到的HttpClient。

例如

服务方法

@Injectable({ providedIn: 'root' }) //ensure service is provided at root level so it remains a singleton in the dependency injection tree.
...
constructor(http: HttpClient){}
...
processData(id): Observable<any> { //services should return an Observable
    const url = `http://localhost:5000/data/${id}`;
    return this.http.head(url); // ** your service method SHOULDN'T be subscribing to the HTTP call.
}

您的服务方法不应订阅HTTP调用。 调用.subscribe()将导致发出HTTP请求。

使用此服务的组件将首先将该服务注入到构造函数中。然后,您将在组件中订阅服务呼叫。

SomeComponent.ts

...
constructor(private dataService: DataService){}
...
someMethod(){
   this.processData().subscribe(
       (response) => { //subs
           console.log("success");
           // Rest of the code - TODO
       },
       (error) => {
           console.log('Failed');        

          // Rest of the code - TODO
       }
   )
}

然后,您的测试用例应该像组件一样订阅该服务。

service.spec.ts-您的服务测试案例

fit('should be valid', fakeAsync(() => {
   const id = 1;

   service.subscribe( //you are making the http call in the test case.
       (success: any) => {
          expect(success.request.headers.get('Content-Type').toEqual('application/json')); //assert that the http headers you will get back from the observable is similar to the one the mock backend will return.
       }
   )

   httpMock.expectOne({
      url: 'http://localhost:5000/data/${id}',
      method: 'HEAD'
   }).flush({}, { headers: { 'Content-Type': 'application/json' } }); //HEAD requests have empty response body but only headers

});

此外,您不应该调用localhost,当您必须将此应用程序部署到Web服务器时,则必须手动更改每个字符串。

相反,您应该在环境文件中设置API网址,该文件位于:

然后,您可以通过以下方式将环境网址作为字符串导入:

import { environment } from 'environments/environment';
...
const API_URL = environment.apiURL;

以下是一些对我有所帮助的指南,并且我已将其添加为书签: 使用angular的HttpClient模块发送HTTP请求: https://www.techiediaries.com/angular-httpclient/

测试服务: https://www.ng-conf.org/2019/angulars-httpclient-testing-depth/

相关问题