问题
Total novice at Karma/Jasmine looking for some assistance. I'm trying to run the following test and I get the error "Cannot make XHRs within a fake async test". I have included the test and the method I am attempting to call. Any help is greatly appreciated.
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');
})));
});
The method I am calling reads
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;
}
);
}
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/46544576/cannot-make-xhrs-from-within-a-fake-async-test