简体   繁体   English

在Angular 4中模拟HTTP请求

[英]mock http request in Angular 4

I write an app in Angular 4 and I've got ngOnInit function with http get request. 我在Angular 4中编写了一个应用程序,并且具有ngOnInit函数和http get请求。 I want to write unit test, but don't know how to mock the request. 我想编写单元测试,但不知道如何模拟请求。

ngOnInit() {
this.http.get<any>('someurl', {
  headers: new HttpHeaders().set('Authorization', 'authorization'`)
})
.subscribe(
  (res) => {
    this.servB = res.items
    .map((item) => {
      return new ServB(item)
    });
  }
);
}

and my unit test so far looks like this: 到目前为止,我的单元测试如下:

beforeEach(async(() => {
TestBed.configureTestingModule({
  imports: [ HttpClientModule, HttpModule ],
  declarations: [ ServBComponent ],
  providers : [ 
    { provide: 'someurl', useValue: '/' },
    { provide: XHRBackend, useClass: MockBackend }
  ]
})
.compileComponents().then(() => {
  fixture = TestBed.createComponent(ServiceBrokersComponent);
  component = fixture.componentInstance;
});
it('should get the servb list', async(inject([XHRBackend], (mockBackend) => {
  mockBackend.connections.subscribe((connection) => {
    connection.mockRespond(new Response(new ResponseOptions({
      body: data
    })));
  }); 
  fixture.detectChanges();
  fixture.whenStable().then(()=> {
    console.log('anything');
  });
})));

but it doesn't work. 但这不起作用。 It still requests data from the server, doesn't return the mocked value. 它仍然从服务器请求数据,不返回模拟值。 Plus everything that is after 'whenStable()' is executed before... What am I doing wrong? 加上在执行“ whenStable()”之后的所有操作……我在做什么错?

You need to import HttpClientTestingModule instead of HttpClientModule , like this: 您需要导入HttpClientTestingModule而不是HttpClientModule ,如下所示:

beforeEach(() => {
  TestBed.configureTestingModule({
    imports: [HttpClientTestingModule],
    providers: [
      HttpService
    ]
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM