Search code examples
angularangular-test

Angular 2 - Test component with ChangeDetectorRef dependency


i'm trying to testing a component with ChangeDetectorRef

constructor(private cdRef: ChangeDetectorRef) {}

And this is the spec file

import {RTLateralMenuComponent} from "./RTLateralMenu.component";

describe('RTLateralMenuComponent', () => {
  let app: RTLateralMenuComponent;

  beforeEach(()=>{
    app = new RTLateralMenuComponent();
  });
});

new RTLateralMenuComponent obviously expect an argument, but i don't how it works.


Solution

  • You can mock it

    const cdRefMock = {
      detectChanges: () => null
    };
    
    app = new RTLateralMenuComponent(cdRefMock);
    

    You will have to implement every method used in your component : detectChanges being the most common one, I thought I would give it right away.

    (PS : I assumed you don't use the testbed since you're creating an instance of your component)