BalB
BalB

Reputation: 127

Can't build testing module with translate

I'm trying to test a component that uses the translate pipe from ngx-translate and can't build the testing module.

component.html

<div class="container">
    <div class="row">
      <div class="col-12 my-4">
        <h1>
          {{'private.title' | translate }}
        </h1>
      </div>
    </div>
</div>

component.ts

....

  constructor(
    public itemsService: ItemsService,
    private sortPipe: OrderByPropertyNamePipe,
    private cdr: ChangeDetectorRef,
    private modalService: ModalService
  ) { }

....

So as you can see nothing regarding ngx-translate is being used other than the translate pipe in the HTML file.

component.spec.ts file

describe('Component', () => {
  describe('Default', () => {
    let component: Component;
    let fixture: ComponentFixture<Component>;
    let debugElement: DebugElement;
    beforeEach(
      waitForAsync(() => {
        TestBed.configureTestingModule({
          imports: [
            HttpClientTestingModule,  
            TranslateModule.forRoot(),
          ],
          providers: [
            ItemsService,
            OrderByPropertyNamePipe,
          ],
        })
        .overrideComponent(Component, {
          set: { changeDetection: ChangeDetectionStrategy.Default }
        })
        .compileComponents();
      }),
    );
    beforeEach(() => {
      fixture = TestBed.createComponent(Component);
      component = fixture.componentInstance;
      debugElement = fixture.debugElement;
      component.allItems = MOCK_ITEMS;

      fixture.detectChanges();
    });

    it('should create', () => {
      expect(component).toBeTruthy();
    });
  });
});

throws

NG0302: The pipe 'translate' could not be found!

I have tried creating mock pipe as https://stackoverflow.com/a/57604396/8889351 but doesn't work either

anybody has a clue on how to build correctly testing module?

thanks in advance

Upvotes: 0

Views: 490

Answers (1)

Gerardo Gonzalez
Gerardo Gonzalez

Reputation: 111

Add the translateService into your providers

first import into your spec file

import { TranslateModule, TranslateService } from '@ngx-translate/core';

and add it here

   imports: [
        HttpClientTestingModule,  
        TranslateModule.forRoot(),
   ],
   providers: [
        TranslateService,
        ItemsService,
        OrderByPropertyNamePipe
   ],

Thats how I test in my project

Upvotes: 1

Related Questions