Chr*_*ris 5 unit-testing karma-runner karma-mocha angular
当我运行测试时,出现 NullInjectorError: Noprovider for HttpClient 。
将 Angular 8 与 Karma 结合使用。我遵循了一些例子,并且对 Karma 很陌生。所以不确定为什么会发生这种情况。为什么?
我读到的大部分内容都说包含 httpclienttesting 模块。但这似乎并没有什么区别。
我的 getHelpfulLinks 组件 -
import { Component, OnInit } from '@angular/core';
import { TkDataService } from '../tk-services/tk-data/tk-data.service';
@Component({
selector: 'app-tk-helpful-links',
templateUrl: './tk-helpful-links.component.html',
styleUrls: ['./tk-helpful-links.component.scss']
})
export class HelpfulLinksComponent implements OnInit {
public res: {};
getHelpfulLinks(): any {
return this.dataSvc.get('gethelpfulLinks', {})
.subscribe(res => {
this.res = res;
});
}
constructor(
private dataSvc: TkDataService
) {
}
ngOnInit() {
this.getHelpfulLinks();
}
}
}
Run Code Online (Sandbox Code Playgroud)
还有我的 .spec 文件 -
import { async, ComponentFixture, TestBed, inject } from '@angular/core/testing';
import { HelpfulLinksComponent } from './tk-helpful-links.component';
import { TkDataService } from '../tk-services/tk-data/tk-data.service';
import { HttpClient} from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import {HttpClientModule} from '@angular/common/http';
describe('HelpfulLinksComponent', async() => {
let component: HelpfulLinksComponent;
let http: HttpClient;
let mockTkDataService = new TkDataService(http);
let httpTestingController: HttpTestingController;
let fixture;
beforeEach(async () => {
fixture = TestBed.createComponent(HelpfulLinksComponent);
component = fixture.componentInstance;
fixture.detectChanges();
TestBed.configureTestingModule({
declarations: [ HelpfulLinksComponent ],
imports: [ HttpClientTestingModule ],
})
.overrideComponent(HelpfulLinksComponent, {
set: {
providers: [
{ provide: TkDataService, useValue: mockTkDataService }
]
}
})
.compileComponents();
httpTestingController = TestBed.get(HttpTestingController);
component = TestBed.get(mockTkDataService);
afterEach(() => {
httpTestingController.verify();
});
});
it('HelpfulLinksComponent should be created', () => {
expect(component).toBeTruthy();
});
});
Run Code Online (Sandbox Code Playgroud)
我的 TKDataService 文件(部分)-
export class TkDataService {
constructor(
private http: HttpClient
) {
}
get(route: string, data: any, responseType?): Observable<any[]>{
const observe = responseType === 'blob' ? 'response' : 'body';
let requestHeaders = new HttpHeaders();
requestHeaders = requestHeaders.set('Authorization', localStorage.getItem('bearerToken'));
// tslint:disable-next-line: max-line-length
return this.http.get<any[]>(environment.baseAPIUrl + route,
{withCredentials: false, headers: requestHeaders, responseType, observe: observe as 'body'} );
}
}
Run Code Online (Sandbox Code Playgroud)
简短回答:
您将 null 传递httpClient给mockTkDataService以下行:
let http: HttpClient;
let mockTkDataService = new TkDataService(http);
Run Code Online (Sandbox Code Playgroud)
你应该做什么:
TkDataService你根本不需要嘲笑。这HttpClientTestingModule将解决httpClient它里面的问题。
只需将原始数据添加TkDataService到测试台配置中的提供者数组中,如下所示:
TestBed.configureTestingModule({
declarations: [ HelpfulLinksComponent ],
imports: [ HttpClientTestingModule ],
providers: [ TkDataService ]
})
Run Code Online (Sandbox Code Playgroud)
稍后像这样使用它:
const tkDataService = getTestBed().get(TkDataService)
httpService.get<any>(dummyUrl, dummyTelemetryAction).subscribe(
(response: HttpResponse<any>) => {
expect(response).toBeTruthy();
}
const req1 = httpMock.expectOne(dummyUrl);
req1.flush(null, { status: 200, statusText: 'ok' });
Run Code Online (Sandbox Code Playgroud)