[英]How to Inject a Service with Parameterized constructor to a Component - Angular
[英]How to test component with a @Inject text in the constructor in Angular
角度6,我在组件的构造函数中声明了一些注入的变量,但是当我运行ng test
时,我不知道如何在单元测试文件中配置注入的值,并且它给出以下错误:
错误:StaticInjectorError(DynamicTestModule)[标题]:
StaticInjectorError(平台:核心)[标题]:NullInjectorError:没有标题提供者!
//我的组件
export class ConfirmModalComponent extends BaseModal implements OnInit {
choosedCandidates: Array<any> = [];
constructor(
@Inject('title') public title,//injected variable
protected modalService: ModalService
) {
super();
}
ngOnInit() {
}
....
}
//spec file of my component
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ DelInterviewerConfirmModalComponent ],
imports: [ CheckboxModule, TranslateModule ],
providers: [
{ provide: title, useValue: 'modal title' },
ModalService,
RequisitionDetailService ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA ],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(DelInterviewerConfirmModalComponent);
component = fixture.componentInstance;
component.title = "test";
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
我想知道是否有人遇到相同的问题,以及如何解决错误,请先感谢。
日期,数字和字符串之类的值必须包装在Injection Token中 。
1 .:创建注入令牌:
export const TITLE = new InjectionToken<string>('title');
2 .:像现在一样注入:
constructor(@Inject(TITLE) private title: string)
3 .:在您的测试中,使用InjectionToken模拟它:
TestBed.configureTestingModule({
declarations: [ DelInterviewerConfirmModalComponent ],
imports: [ CheckboxModule, TranslateModule ],
providers: [
{ provide: TITLE, useValue: 'modal title' },
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.