How to test pipe injecting the ChangeDetectorRef

Issue

I have a pipe like this one:

@Pipe({name: 'myPipe', pure: false})
export class MyPipe implements PipeTransform {

    constructor(private _ref:ChangeDetectorRef) {
         _ref.markForCheck();
    }

    public transform(input: string | number) {
         return 'something';
    }

}

And here goes my test spec for that pipe:

describe('Pipe: MyPipe', () => {
    let changeDetector: ChangeDetectorRefMock;
    let pipe: MyPipe;
    beforeEach(async() => {
        await TestBed.configureTestingModule({
            providers: [
                MyPipe,
                {
                    provide: ChangeDetectorRef,
                    useClass: ChangeDetectorRefMock
                }
            ];
        }).compileComponents();
        changeDetector = TestBed.inject(ChangeDetectorRef) as ChangeDetectorRefMock;
        pipe = TestBed.inject(MyPipe); // <-- error is thrown (see below)
    });

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

@Injectable()
class ChangeDetectorRefMock {
    public detectChanges(): void {}
}

If I run the testspec, I receive the following error for line pipe = TestBed.inject(MyPipe);:

TypeError: Cannot read properties of null (reading 'type')
    at createViewRef (C:\interne\VEBLuZ\packages\core\src\change_detection\change_detector_ref.ts:163:20)
    [...]
    at C:\exampleProject\libs\example-lib\src\pipe\my.pipe.spec.ts:22:20

How to write a testclass for this pipe with injection of ChangeDetectorRef?

Solution

The answer is quite simple! You do not inject a pipe, but create it via it’s constructor:

 pipe = new MyPipe(changeDetector);

Answered By – MojioMS

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.