How to mock Pipe when testing Component

风流意气都作罢 提交于 2019-12-03 02:06:55

You can add your mockpipes in the declarations of the TestBed:

TestBed.configureTestingModule({
            declarations: [
                AppComponent,
                MockPipe
            ],
           ...

The MockPipe needs to have the @Pipe decorator with the original name.

import {Pipe, PipeTransform} from '@angular/core';

@Pipe({name: 'pipename'})
class MockPipe implements PipeTransform {
    transform(value: number): number {
        //Do stuff here, if you want
        return value;
    }
}

To stub the pipe, use Dinistro's answer. To spy on the pipe, you can complement that with the following:

let pipeSpy: jasmine.Spy;

beforeEach(() => {
    TestBed.configureTestingModule...

    pipeSpy = spyOn(MockPipe.prototype, 'transform');
};

it('should do whatever', () => {
    doYourStuff();

    expect(pipeSpy).toHaveBeenCalled();
}

If you want reusable util function for mocking pipes, you can try this option:

export function mockPipe(options: Pipe): Pipe {
    const metadata: Pipe = {
      name: options.name
    };

    return <any>Pipe(metadata)(class MockPipe {});
}

And then just call this function inside the TestBed declarations array:

TestBed.configureTestingModule({
    declarations: [
        SomeComponent,
        mockPipe({ name: 'myPipe' }),
        mockPipe({ name: 'myOtherPipe' })
    ],
    // ...
}).compileComponents();
Pavel Pazderník

Mocking my pipe into simple class like

export class DateFormatPipeMock {
 transform() {
  return '29.06.2018 15:12';
 }
}

and simple use of useClass in my spec file

providers: [
  ...
  {provide: DateFormatPipe, useClass: DateFormatPipeMock}
  ...
]

worked for me :-)

You can use MockPipe function, but you need to import it like below.

import { MockPipe } from 'mock-pipe';

After that, all you need to do is to define your mock pipe in providers..

providers: [
{ provide: HighlightPipe, useValue: MockPipe(HighlightPipe, () => 'mock') } ]

That's all.

Often, we use pipes in templates. Here’s how you can mock a pipe. Note that the name of the pipe has to be the same as the pipe you are mocking.

@Pipe({ name: 'myPipe' })
class MyPipeMock implements PipeTransform {
  transform(param) {
    console.log('mocking');
    return true;
  }
}

You need to include the pipe when configuring your TestingModule if you are using it in a component’s template in the declarations.

One possibility is to use the ng-mocks library and use it like this:

TestBed.configureTestingModule({
  declarations: [
    TestedComponent,
    MockPipe(ActualPipe, (...args) => args[0]),
  ]
}).compileComponents();

The second argument to MockPipe defines what the transform function returns for an array of args.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!