如何在Angular的构造函数中使用@Inject文本测试组件

Che*_*ess 5 unit-testing angular

Angular 6,我在组件的构造函数中声明了一些注入的变量,但是我不知道如何在单元测试文件中配置注入的值,当我运行时ng test,它给出了以下错误:

错误:StaticInjectorError(DynamicTestModule)[title]:
StaticInjectorError(Platform: core)[title]: NullInjectorError: No provider for title!

//我的组件

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();
});
Run Code Online (Sandbox Code Playgroud)

我想知道是否有人遇到同样的问题以及如何解决错误,提前致谢。

Dán*_*rta 4

日期、数字和字符串等值必须包装到注入令牌中。

1.:创建注入令牌:

export const TITLE = new InjectionToken<string>('title');
Run Code Online (Sandbox Code Playgroud)

2.:像现在一样注射:

constructor(@Inject(TITLE) private title: string)
Run Code Online (Sandbox Code Playgroud)

3.:在您的测试中,使用 InjectionToken 模拟它:

  TestBed.configureTestingModule({
      declarations: [ DelInterviewerConfirmModalComponent ],
      imports: [ CheckboxModule, TranslateModule ],
      providers: [ 
        { provide: TITLE, useValue: 'modal title' },
Run Code Online (Sandbox Code Playgroud)