Angular 无法从假异步测试中生成XHR

Angular 无法从假异步测试中生成XHR,angular,karma-jasmine,Angular,Karma Jasmine,Karma/Jasmine完全是新手,正在寻求帮助。我正在尝试运行下面的测试,结果出现错误“无法在假异步测试中生成XHR”。我已经包括了测试和我试图调用的方法。非常感谢您的帮助 import... fdescribe('CageService', () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule,

Karma/Jasmine完全是新手,正在寻求帮助。我正在尝试运行下面的测试,结果出现错误“无法在假异步测试中生成XHR”。我已经包括了测试和我试图调用的方法。非常感谢您的帮助

import...

fdescribe('CageService', () => {

beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [
            RouterTestingModule,
            HttpModule
        ],
        providers: [
            BaseRequestOptions,
            MockBackend,
            CageService,
            { provide: 'appHttpService', useClass: AppHttpService },
            { provide: 'appHttpHelperService', useClass: AppHttpHelperService },
            { provide: 'appUtilityService', useClass: AppUtilityService },
            { provide: Http, useFactory: (backend: ConnectionBackend, defaultOptions: BaseRequestOptions) => {
                return new Http(backend, defaultOptions);
            }, deps: [MockBackend, BaseRequestOptions] }
        ]
    });
});

it('will load cages', inject([CageService, MockBackend], fakeAsync(( cageService, mockBackend\) => {

    var res;
    mockBackend.connections.subscribe( c => {

        expect(c.request.url).toBe('http://example.com');
        let response = new ResponseOptions( { body: '{"name": "charles"}' } );
        c.mockRespond( new Response( response ) );
    });

    cageService.load({}).subscribe((_res) => {

        res = _res;
    });

    tick(100);
    discardPeriodicTasks();
    expect(res.name).toBe('Charles');
})));
});
我调用的方法读取

load ( criteria: Object ) {

    return this.appHttpService.get( this.url + '?' + criteria )
    .map( 

        response => {

            let data = response.json();

            this.pagination.total = data.count;
            this.pagination.per_page = data.limit;
            this.pagination.current_page = data.currentPage;
            this.pagination.last_page = data.totalPages;

            let cages = [];
            for( let x = 0; x < data.rows.length; x++ ) {

                cages.push( this.formatCage(new Cage(), data.rows[x] ) );
            }

            this._cages$.next( this.dataStore.cages );

            return data.rows;
        }
    );
}
加载(条件:对象){
返回此.appHttpService.get(this.url+'?'+条件)
.地图(
响应=>{
让data=response.json();
this.pagination.total=data.count;
this.pagination.per_page=data.limit;
this.pagination.current_page=data.currentPage;
this.pagination.last_page=data.totalPages;
让笼子=[];
for(设x=0;x
我也遇到了同样的问题,我不确定您使用的angular是什么版本,但这适用于中的
HttpClientModule
,不确定它是否适用于
HttpModule
。以下是我的版本:

@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
这是我的
导入
提供程序
数组:

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

如果您还没有使用
HttpClient
,它可能值得更新,因为它更易于使用。希望这有帮助

角度6+解决方案。

首先,对于angular 6+,我们必须使用拦截器来处理这个问题。 您需要创建一个实现HttpIntercepter的服务,只需重写“intercept”方法,它就可以返回任何您想要的值

我面临着同样的错误,我的解决方案是

      @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();
      }));
@Injectable()
类TestHttpRequestInterceptor实现HttpInterceptor{
拦截(请求:HttpRequest,下一步:HttpHandler):
可观察{
返回新的可观察对象(观察者=>{
observer.next({}作为HttpEvent);
});
}
}
beforeach(异步(()=>{
TestBed.configureTestingModule({
导入:[共享模块,路由测试模块,
StoreModule.forRoot(来自reducers.reducer))
],
声明:[],
供应商:[
LocalStorageService,
{
提供:HTTP_拦截器,useClass:TestHttpRequestInterceptor,multi:true
}
],
模式:[无错误模式,自定义元素模式]
})
.compileComponents();
}));
希望代码能有所帮助