How to test components with ngx-translate's TranslatePipe? TypeError: Cannot read properties of undefined (reading 'subscribe')

How to test components with ngx-translate's TranslatePipe? TypeError: Cannot read properties of undefined (reading 'subscribe')

我有一个组件,它本身不会将 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 而失败。现在我不确定如何解决这个问题。有什么想法吗?

好的,一如既往,我在这里抱怨后找到了答案。

我删除了 TranslationServiceStub 和 TranslatePipe 并添加了

        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useClass: TranslateFakeLoader,
          }
        })

到进口。现在可以了。