我正在为使用多个内部组件的自定义表模块编写单元测试。所有内部组件都使用 ForwardRef 来访问主表的输入,例如列。在 TestBed 中导致问题的组件是 TableBody,它注入运行 HTTP 请求的配置服务:
import { ConfigService } from '../services/config.service';
@Component({
selector: 'custom-table',
template: `...
<tbody [customTableBody]="dt.columns"...
`
})
export class Table {
_columns: any[];
@Input() get columns(): any[] {
return this._columns;
}
set columns(cols: any[]) {
this._columns = cols;
...
}
@Component({
selector: 'customTableBody',
template: `...`
})
export class TableBody implements OnInit {
_user: any;
@Input("customTableBody") columns: Column[];
constructor(@Inject(forwardRef(() => Table)) public dt: Table, private config?: ConfigService) { }
ngOnInit() {
this._user = this.config.getUser();
};
...
}
@NgModule({
exports: [Table],
declarations: [Table, TableBody,...]
})
export class TableModule { }
测试设置,设置多个自定义表来测试不同的内部组件,创建并提供模拟配置服务:
@Component({
template: `
<custom-table class="basicTable"...
<custom-table class="specialTable"...`
})
class TestTableComponent {...}
describe("CustomTable", () => {
let fakeConfigService: jasmine.SpyObj<ConfigService>;
beforeEach(() => {
fakeConfigService = jasmine.createSpyObj<ConfigService>('ConfigService', ['getUser']);
fakeConfigService.getUser.and.returnValue("TESTUSER");
TestBed.configureTestingModule({
imports: [
TableModule
],
providers: [
{ provider: ConfigService, useFactory: () => fakeConfigService }
],
declarations: [
TestBasicTableComponent, TableBody
]
});
...}
但是,即使当我声明假服务的提供者、导入 TableModule 并声明 TableBody 时,它似乎仍然没有真正向内部组件提供假服务,而是尝试导入真实的服务并失败,并显示
NullInjectorError: R3InjectorError(DynamicTestModule)[ConfigService -> HttpClient -> HttpClient]: NullInjectorError: No provider for HttpClient!
。我是否缺少一些可以让提供程序在内部组件上工作的东西?
请在导入中添加
HttpClientTestingModule
!
import { HttpClientTestingModule } from '@angular/common/http/testing';
...
...
TestBed.configureTestingModule({
imports: [
TableModule,
HttpClientTestingModule
],
providers: [
...