2

I have a component which itself does not inject the TranslationService into the constructor. But I use the translate pipe in the html files. The test always fails with this error:

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)

My test looks like this:

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

Before I added the TranslationServiceStub it failed due to missing TranslationService. Now I am not sure how to fix this. Any ideas?

Apollo
  • 1,296
  • 2
  • 11
  • 24

1 Answers1

4

Okay, as always, I found the answer after complaining here.

I removed the TranslationServiceStub and the TranslatePipe and added

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

to the imports. Now it works.

Apollo
  • 1,296
  • 2
  • 11
  • 24
  • 1
    thank you a lot ! it works great ! Just a question: how did you find the answer ? by reading this ? https://github.com/ngx-translate/core/blob/master/projects/ngx-translate/core/tests/translate.pipe.spec.ts#L53 – Joand Apr 04 '22 at 13:51