mock http request in Angular 4

2019-06-09 13:47发布

问题:

I write an app in Angular 4 and I've got ngOnInit function with http get request. 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?

回答1:

You need to import HttpClientTestingModule instead of HttpClientModule, like this:

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