【问题标题】:mock http request in Angular 4Angular 4中的模拟http请求
【发布时间】:2017-10-16 12:08:57
【问题描述】:

我在 Angular 4 中编写了一个应用程序,并且我有带有 http get 请求的 ngOnInit 函数。我想写单元测试,但不知道如何模拟请求。

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

到目前为止,我的单元测试如下所示:

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

但它不起作用。它仍然从服务器请求数据,不返回模拟值。加上'whenStable()'之后的所有内容都在之前执行......我做错了什么?

【问题讨论】:

    标签: angular unit-testing jasmine karma-jasmine


    【解决方案1】:

    你需要导入HttpClientTestingModule而不是HttpClientModule,像这样:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 2018-03-30
    相关资源
    最近更新 更多