Home > Blockchain >  Why can I not mock a pipe that is used in a component's template?
Why can I not mock a pipe that is used in a component's template?

Time:10-13

I am trying to write a component test that has a mock pipe which is intended to be substituted for the actual pipe that is used in the template.

When the component is rendered in the test world, its template, which is doing: {{ name | hello }} results in the actual real-world pipe, not the mock pipe.

If I use dependency injection via the constructor for the component:

constructor(public p: HelloPipe) {}

I see that this p property is in fact the MockPipe class that I am expecting, however for some reason I don't understand, the usage of the pipe in the component's template is not getting the same pipe that is provided by the injector...

I have made a stackblitz to illustrate the problem.

Please look at the hello.component.spec.ts file and you will see in the it('works') spec at the bottom, I have a comment highlighting that the p property coming from the injector IS the mocked pipe, however the text rendered from the html {{ name | hello }} is using the real pipe, not the mock.

How can I get the template to use the mocked pipe instead of the real one?

CodePudding user response:

You need to make a few changes to the test bed config and the mock pipe to make it work on the template

  • Remove the HelloModule import so that the real pipe is not imported
  • Change mock pipe so that it has the name metadata
  • Add the mock pipe in the declarations array
@Pipe({
  name: 'hello',
})
export class MockPipe implements PipeTransform {
  transform(value: string) {
    return 'mocked!';
  }
}

TestBed.configureTestingModule({
  imports: [CommonModule],
  declarations: [HelloComponent, MockPipe],
  providers: [{ provide: HelloPipe, useClass: MockPipe }],
}).compileComponents();
  • Related