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

Angular 包含HTTP订阅的服务方法的测试用例-HTTP RxJs,angular,unit-testing,karma-jasmine,angular-test,httptestingcontroller,Angular,Unit Testing,Karma Jasmine,Angular Test,Httptestingcontroller,我有一个服务方法,它有一个服务调用HTTP调用,它立即订阅,并根据响应代码执行动作命令的其余部分 示例:服务方法 processData(id): void { const url = `http://localhost:5000/data/${id}`; this.http.head(url).subscribe(() => { console.log('Success'); // Rest of the code - TODO

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

示例:服务方法

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

    });
}
我尝试了以下示例测试用例

fdescribe('ReportedFileService', () => {

    let service: DataService;
    let httpMock: HttpTestingController;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports:[HttpClientModule, HttpClientTestingModule],
            providers:[DataService]
        });
        service = TestBed.get(DataService);
        httpMock = TestBed.get(HttpTestingController);
    });

    afterEach(() => {
        httpMock.verify();
    });

    fit('should be valid', () => {
        const id = 1;
        const filePath = `http://localhost:5000/data/${id}`;

        const req = httpMock.expectOne(filePath);

        expect(req.request.method).toEqual('Head');

        const response = service.processData(id);
    })
}

请帮助我如何处理这种情况。

您的服务不应该订阅HttpClient observable,因此,它不应该是无效的返回类型方法。服务应返回要订阅的HttpClient observable

例如

服务方式

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

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

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

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

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

src/environments/environment.prod.ts-包含实际域。例如。 src/environments/environment.ts-包含本地主机、本地开发服务器,例如${id} 然后将环境URL作为字符串以以下方式导入:

import { environment } from 'environments/environment';
...
const API_URL = environment.apiURL;
以下是一些帮助过我的指南,我已将其添加到书签中: 使用angular的HttpClient模块发送HTTP请求:

测试服务:

感谢您提供宝贵的信息,您需要花时间在线查看代码。我放弃了投票,一旦我得到结果,我会批准它作为答案。嗨,一旦我触发了刷新方法,chrome浏览器就会断开连接。请帮助我的头部请求我的坏,我忘了这是一个头部请求。我已经为模拟后端编辑了我的答案,以作为HEAD请求返回头和空的http正文。订阅应测试返回的头是否符合预期。关于规格,请看一下我仍然面临的问题。我在另一个问题中发布了详细信息。我已经阅读了您的新问题,但您的服务方法仍然不正确。也许我解释得不够好,我进一步编辑了我的答案。
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

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