Angular 6单元测试http获取请求 [英] Angular 6 unit testing a http get request

查看:228
本文介绍了Angular 6单元测试http获取请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件,其中有一个类似以下功能的请求:

I have a component where I have a request in a function like:

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

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

It returns me an object array in subscription like:

[{name: 'a'}, {name: 'b'}]

或类似的东西.

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

I wanted to write a test that makes sure getData() calls http GET once with the proper url and the subscription returns something array-like.

我的代码:

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

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

I failed the test with this message: "Expected no open requests, found 1: GET /app/data"

推荐答案

首先,按照良好的做法,您应该将组件与发出请求本身分开,而应使用Service,因为从长远来看,它将发现它更清洁应用程序的增长是为了处理API请求.

First off for good practices you should separate your component from making the request itself and use a Service instead as you will find it more cleaner in the longer run as your app grows for services to handle API requests.

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

This is another approach you can do for getting it to work with the HttpTestingController as I'm not quite sure why your inject of the controller is not working.

通过这种变通方法,只需测试服务即可,或者只是使用相同的方法在组件测试中构建组件.

simply test the service instead or just structure your component the same approach on your component tests with this workaround.

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

get your data from the service by injecting it to the component.

组件:

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

服务:

@Injectable()
export class TestService {

  constructor(private http: HttpClient) { }

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

}

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

then test the service in this way instead, it's just as your component test but just using the service instead

测试:

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

});

这是测试

这篇关于Angular 6单元测试http获取请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆