Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock Pipe when testing Component

Currently I am overriding providers to use mocked services like this:

beforeEach(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {     tcb.overrideProviders(AddFieldToObjectDropdownComponent,         [              provide(ServiceA, { useClass: MockServiceA })),              provide(ServiceB, { useClass: MockServiceB }))         ])     ... 

I want to do same thing for pipes that the component uses. I tried, provide(PipeA, { useClass: MockPipeA }) and provide(PipeA, { useValue: new MockPipeA() }) but both didn't work.

like image 323
harunurhan Avatar asked Sep 02 '16 13:09

harunurhan


People also ask

How do you mock a pipe?

A mock pipe in Angular tests can be created by MockPipe function. The second parameter of the function accepts a custom transform callback. The mock pipe has the identical interface as its source pipe, but all its methods are dummies. To provide a mock pipe in a test, pass this source pipe into MockPipe function.

How is testing done in Angular?

To run the test, you will only need to run the command ng test . This command will also open Chrome and run the test in watch mode, which means your test will get automatically compiled whenever you save your file. In your Angular project, you create a component with the command ng generate component doctor .


1 Answers

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;     } } 
like image 69
Dinistro Avatar answered Sep 18 '22 14:09

Dinistro