簡體   English   中英

如何在Angular的構造函數中使用@Inject文本測試組件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM