3

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.

  • 1
    Please read angular unit test guide. You will get to know better ways to do it https://angular.io/guide/testing#component-test-basics – Amit Chigadani Aug 02 '18 at 09:01
  • I started to read the guide, but this error appears immediately –  Aug 02 '18 at 09:03
  • Does this answer your question? [Angular 2: How to mock ChangeDetectorRef while unit testing](https://stackoverflow.com/questions/41421807/angular-2-how-to-mock-changedetectorref-while-unit-testing) – Alex Parloti Jun 08 '20 at 08:51

1 Answers1

4

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)

  • The following error appears: ''Property markforcheck is missing in type { detectChanges: () => null }". –  Aug 02 '18 at 09:05
  • Then add `markforcheck` in your mock. I told you to put every method you use in your mock. –  Aug 02 '18 at 09:06
  • No problem, I'm here for that ! –  Aug 02 '18 at 09:10