Cannot make XHRs from within a fake async test

烈酒焚心 提交于 2019-12-04 14:32:50

I had the same issue, and I'm not sure what version of angular you're using, but this works with HttpClientModule in , not sure if it works with HttpModule. Here are my versions:

@angular/cli: 1.4.9
node: 8.8.1
os: linux x64
@angular/animations: 4.4.6
@angular/cdk: 2.0.0-beta.12
@angular/common: 4.4.6
@angular/compiler: 4.4.6
@angular/core: 4.4.6
@angular/forms: 4.4.6
@angular/http: 4.4.6
@angular/material: 2.0.0-beta.12
@angular/platform-browser: 4.4.6
@angular/platform-browser-dynamic: 4.4.6
@angular/router: 4.4.6
@angular/cli: 1.4.9
@angular/compiler-cli: 4.4.6
@angular/language-service: 4.4.6
typescript: 2.5.3

And here is my imports & providers array:

import { MockBackend } from '@angular/http/testing';
import { HttpClientModule, HttpXhrBackend } from '@angular/common/http';
imports: [
    otherStuff...,
    HttpClientModule
],
providers: [
    otherStuff...,
    SomeService,
    {
        provide: HttpXhrBackend,
        useClass: MockBackend
    }
]

If you're not using HttpClient yet, it may be worth updating as it's much easier to use. Hope this helps.

Angular 6+ solution.

First of all for angular 6+ we have to use Interceptors to deal with that. You need to create a service that implements HttpIntercepter and just override 'intercept' method, it should return Observer with any value you want.

I faced with same error, and my solution is

      @Injectable()
      class TestHttpRequestInterceptor implements HttpInterceptor {

        intercept(req: HttpRequest<any>, next: HttpHandler):
          Observable<HttpEvent<any>> {
          return new Observable<any>(observer => {
              observer.next({} as HttpEvent<any>);
          });
        }
      }

   beforeEach(async(() => {
        TestBed.configureTestingModule({
          imports: [SharedModule, RouterTestingModule,
            StoreModule.forRoot(fromReducers.reducer))
          ],
          declarations: [],
          providers: [
            LocalStorageService, 
            {
              provide: HTTP_INTERCEPTORS, useClass: TestHttpRequestInterceptor, multi: true
            }
            ],
          schemas: [NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA]
        })
          .compileComponents();
      }));

Hope that code will help.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!