Angular 6单元测试http获取请求

Bál*_*thy 1 unit-testing angular

我有一个组件,其中我在一个函数中有一个请求:

getData():Observable<any>{
    return this._http.get('/app/data', {observe: 'response'});
}
Run Code Online (Sandbox Code Playgroud)

它向我返回订阅中的对象数组,例如:

[{name: 'a'}, {name: 'b'}]
Run Code Online (Sandbox Code Playgroud)

或类似的东西。

我想编写一个测试,以确保getData()使用正确的url一次调用http GET,并且预订返回类似数组的内容。

我的代码:

...
    it('getData() should http GET names', () => {
        inject([HttpTestingController], (httpMock: HttpTestingController) => {

          const names = [{name: 'a'}, {name: 'b'}];

          component.getData().subscribe((res) => {
            expect(res).toEqual(names);
          });

          const req = httpMock.expectOne('/app/data');
          expect(req.request.method).toEqual("GET");
          req.flush(names);

          httpMock.verify();
        });
      });
...
Run Code Online (Sandbox Code Playgroud)

我的测试失败,并显示以下消息:“预期没有打开的请求,发现1:GET / app / data”

Luc*_*cho 5

首先,出于良好做法的考虑,您应该将组件与发出请求本身分开,而应使用服务,因为随着应用程序处理API请求的服务的增长,您会发现从长远来看它会更清洁。

这是您可以使它与HttpTestingController一起使用的另一种方法,因为我不确定为什么您对控制器的注入不起作用。

只需测试服务即可,或者使用这种解决方法在组件测试中以相同的方法构建组件。

通过将数据注入到组件来从服务中获取数据。

零件:

@Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  constructor(private service: TestService)
}
Run Code Online (Sandbox Code Playgroud)

服务:

@Injectable()
export class TestService {

  constructor(private http: HttpClient) { }

  getData(): Observable<any>{
    return this.http.get('/app/data');
  }

}
Run Code Online (Sandbox Code Playgroud)

然后以这种方式测试服务,就像您的组件测试一样,只是使用服务

测试:

describe('TestService', () => {

  let httpMock: HttpTestingController;
  let testService: TestService;

  beforeEach(() => {

    TestBed.configureTestingModule({
        imports: [ HttpClientTestingModule ],
        providers: [ TestService ]
    });

    testService = TestBed.get(TestService);
    httpMock = TestBed.get(HttpTestingController);

  });

  it('getData() should http GET names', () => {

    const names = [{name: 'a'}, {name: 'b'}];

    testService.getData().subscribe((res) => {
      expect(res).toEqual(names);
    });

    const req = httpMock.expectOne('/app/data');
    expect(req.request.method).toEqual("GET");
    req.flush(names);

    httpMock.verify();
  });

});
Run Code Online (Sandbox Code Playgroud)

这里是测试在行动