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

标签 angular unit-testing

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

Error: 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();
});

我想知道是否有人遇到同样的问题以及如何解决错误,在此先感谢。

最佳答案

日期、数字和字符串等值必须包含在 Injection Token 中。 .

1.:创建注入(inject) token :

export const TITLE = new InjectionToken<string>('title');

2.:像现在这样注入(inject):
constructor(@Inject(TITLE) private title: string)

3.:在您的测试中,使用 InjectionToken 模拟它:
  TestBed.configureTestingModule({
      declarations: [ DelInterviewerConfirmModalComponent ],
      imports: [ CheckboxModule, TranslateModule ],
      providers: [ 
        { provide: TITLE, useValue: 'modal title' },

关于angular - 如何在Angular的构造函数中使用@Inject文本测试组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56250733/

相关文章:

unit-testing - Angular2 在单元测试中注入(inject) ElementRef

angular - 配置 SystemJS 以加载我的 Angular 2 组件

angular - 使用 ngx-bootstrap modal 将数据传递给 modal

angular - 使用 ngx-bootstrap 的 Bootstrap 下拉菜单

angular - ngOnDestroy 在退出前警告用户

typescript - Angular2 - typescript : Increment a number after timeout in AppComponent

c# - VS 测试资源管理器未找到我的单元测试 (XUnit.Runner) ASP.NET 5

unit-testing - Fluent NHibernate - HiLo 方案的 PersistenceSpecification

c# - 我能否使用 Moq 来验证是否使用复杂参数中的特定值调用了模拟方法?

javascript - 如何对 Angular 1.5 组件中的函数进行单元测试