【发布时间】:2021-11-21 08:29:30
【问题描述】:
我有一个组件,它本身不会将 TranslationService 注入到构造函数中。但我在 html 文件中使用 translate 管道。测试总是失败并出现此错误:
TypeError: Cannot read properties of undefined (reading 'subscribe')
at TranslatePipe.transform (http://localhost:9876/_karma_webpack_/vendor.js:107322:75)
at ɵɵpipeBind1 (http://localhost:9876/_karma_webpack_/vendor.js:80764:22)
at MyComponent_Template (ng:///MyComponent.js:406:33)
at executeTemplate (http://localhost:9876/_karma_webpack_/vendor.js:64582:9)
at refreshView (http://localhost:9876/_karma_webpack_/vendor.js:64448:13)
at refreshComponent (http://localhost:9876/_karma_webpack_/vendor.js:65619:13)
at refreshChildComponents (http://localhost:9876/_karma_webpack_/vendor.js:64245:9)
at refreshView (http://localhost:9876/_karma_webpack_/vendor.js:64498:13)
at renderComponentOrTemplate (http://localhost:9876/_karma_webpack_/vendor.js:64562:9)
at tickRootContext (http://localhost:9876/_karma_webpack_/vendor.js:65793:9)
我的测试如下所示:
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
let httpClient: HttpClient;
let httpTestingController: HttpTestingController;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [
MyComponent,
TranslatePipe,
],
imports: [
HttpClientTestingModule,
RouterTestingModule,
],
providers: [
{
provide: TranslateService,
useClass: TranslationServiceStub,
}
],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
httpClient = TestBed.inject(HttpClient);
httpTestingController = TestBed.inject(HttpTestingController);
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
在我添加 TranslationServiceStub 之前,由于缺少 TranslationService,它失败了。现在我不确定如何解决这个问题。有什么想法吗?
【问题讨论】: