Angular 6, I declare some injected variables in the constructor of my component, But I don't know how to configure the injected value in the unit test file, when I run ng test
and it gives the following error:
Error: StaticInjectorError(DynamicTestModule)[title]:
StaticInjectorError(Platform: core)[title]: NullInjectorError: No provider for title!
//My component
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();
});
I wonder if anybody meets the same problem and how to resolve the errors, thanks in advance.
Values like dates, numbers and string must be wrapped into an Injection Token .
1.: Create an injection token:
export const TITLE = new InjectionToken<string>('title');
2.: Inject like you do now:
constructor(@Inject(TITLE) private title: string)
3.: In your test, mock it using the InjectionToken:
TestBed.configureTestingModule({
declarations: [ DelInterviewerConfirmModalComponent ],
imports: [ CheckboxModule, TranslateModule ],
providers: [
{ provide: TITLE, useValue: 'modal title' },
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.