我正在尝试对具有@viewChild组件和少量其他服务的组件进行单元测试。
以下是我的spec.ts文件。
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ UpStoryComponent,ExperienceListComponent, MdToHtmlPipe, SafeUrlPipe, FormatUrlPipe, CurrencyFormatPipe, NoCommaPipe, MoneyPipe, SafeHtmlPipe],
imports: [ FormsModule, HttpClientTestingModule, RouterTestingModule],
providers: [{ provide: ActivatedRoute, useValue: {'params': Observable.from([{ 'id': 1}])}, ContentfulService, MatchingFlowService, FormDataService, LocalStorageService, ScrollService, Title, UpnorwayLoaderService, MoneyService, DayCalculatorService],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(UpStoryComponent);
component = fixture.componentInstance;
component.experienceListComponent = TestBed.createComponent(ExperienceListComponent).componentInstance;
fixture.detectChanges();
});
beforeEach(() => {
contentfulService = TestBed.get(ContentfulService);
spyOn(contentfulService, 'getEntryBySlug').and.callFake(function (args) {
return of(blogPost);
});
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
最后一条beforeeach语句被执行,但未按预期注入服务。如果我将最后一个beforeeach语句放置为第二个beforeeach语句,那么当前的第二个beforeeach语句将无法按预期执行。
ExperienceListComponent
和ContentfulService
之间没有依赖关系。但是,当通过beforeach语句注入这两个服务时,只有第一个注入有效,而另一个则无效。
这可能是什么原因?感谢您是否可以为此提供解决方案。