37

I have just started with Unit-Testing, and I have been able to mock my own services and some of Angular and Ionic as well, but no matter what I do ChangeDetectorRef stays the same.

I mean which kind of sorcery is this?

beforeEach(async(() => 
    TestBed.configureTestingModule({
      declarations: [MyComponent],
      providers: [
        Form, DomController, ToastController, AlertController,
        PopoverController,

        {provide: Platform, useClass: PlatformMock},
        {
          provide: NavParams,
          useValue: new NavParams({data: new PageData().Data})
        },
        {provide: ChangeDetectorRef, useClass: ChangeDetectorRefMock}

      ],
      imports: [
        FormsModule,
        ReactiveFormsModule,
        IonicModule
      ],
    })
    .overrideComponent(MyComponent, {
      set: {
        providers: [
          {provide: ChangeDetectorRef, useClass: ChangeDetectorRefMock},
        ],
        viewProviders: [
          {provide: ChangeDetectorRef, useClass: ChangeDetectorRefMock},
        ]
      }
    })
    .compileComponents()
    .then(() => {
      let fixture = TestBed.createComponent(MyComponent);
      let cmp = fixture.debugElement.componentInstance;

      let cdRef = fixture.debugElement.injector.get(ChangeDetectorRef);

      console.log(cdRef); // logs ChangeDetectorRefMock
      console.log(cmp.cdRef); // logs ChangeDetectorRef , why ??
    })
  ));

 it('fails no matter what', async(() => {
    spyOn(cdRef, 'markForCheck');
    spyOn(cmp.cdRef, 'markForCheck');

    cmp.ngOnInit();

    expect(cdRef.markForCheck).toHaveBeenCalled();  // fail, why ??
    expect(cmp.cdRef.markForCheck).toHaveBeenCalled(); // success

    console.log(cdRef); // logs ChangeDetectorRefMock
    console.log(cmp.cdRef); // logs ChangeDetectorRef , why ??
  }));

@Component({
  ...
})
export class MyComponent {
 constructor(private cdRef: ChangeDetectorRef){}

 ngOnInit() {
   // do something
   this.cdRef.markForCheck();
 }
}

I have tried everything , async, fakeAsync, injector([ChangeDetectorRef], () => {}).

Nothing works.

Ankit Singh
  • 24,525
  • 11
  • 66
  • 89
  • The ChangeDetectorRef is given special treatment by the Angular 2 compiler. I think you cannot provide it. You can check test for AsyncPipe https://github.com/angular/angular/blob/8f5dd1f11e6ca1888fdbd3231c06d6df00aba5cc/modules/%40angular/common/test/pipes/async_pipe_spec.ts There is used SpyChangeDetectorRef – yurzui Jan 02 '17 at 07:15
  • I'm hitting the same issue - how are people working around this? – SamF Jan 16 '17 at 19:30

6 Answers6

48

Update 2020:

I wrote this originally in May 2017, it's a solution that worked great at the time and still works.

We can't configure the injection of a changeDetectorRef mock through the test bed, so this is what I am doing these days:

 it('detects changes', () => {
      // This is a unique instance here, brand new
      const changeDetectorRef = fixture.debugElement.injector.get(ChangeDetectorRef); 
     
      // So, I am spying directly on the prototype.
      const detectChangesSpy = spyOn(changeDetectorRef.constructor.prototype, 'detectChanges');

      component.someMethod(); // Which internally calls the detectChanges.

      expect(detectChangesSpy).toHaveBeenCalled();
    });

Then you don't care about private attributes or any.


In case anyone runs into this, this is one way that has worked well for me:

As you are injecting the ChangeDetectorRef instance in your constructor:

 constructor(private cdRef: ChangeDetectorRef) { }

You have that cdRef as one of the private attributes on the component, which means you can spy on the component, stub that attribute and have it return whatever you want. Also, you can assert its calls and parameters, as needed.

In your spec file, call your TestBed without providing the ChangeDetectorRef as it won't provide what you give it. Set the component that same beforeEach block, so it is reset between specs as it is done in the docs here:

component = fixture.componentInstance;

Then in the tests, spy directly on the attribute

describe('someMethod()', () => {
  it('calls detect changes', () => {
    const spy = spyOn((component as any).cdRef, 'detectChanges');
    component.someMethod();

    expect(spy).toHaveBeenCalled();
  });
});

With the spy you can use .and.returnValue() and have it return whatever you need.

Notice that (component as any) is used as cdRef is a private attribute. But private doesn't exist in the actual compiled javascript so it is accessible.

It is up to you if you want to access private attributes at runtime that way for your tests.

Juan
  • 6,125
  • 3
  • 30
  • 31
  • so why are you creating private fields when you don't treat them like a private? lol – Stwosch Oct 04 '18 at 12:24
  • 2
    Original question is declared as private. I just answered ;) There is the old discussion of "should I test private methods" with two takes on it, yes and no. Both with valid reasons. My advice is to go with the one that makes you happy. – Juan Oct 04 '18 at 16:23
  • @Juan Why `ChangeDetectorRef ` cannot be provided in a `TestBed` and why to access the private field instead? – Hary May 25 '20 at 15:15
  • 1
    @mbharanidharan88 it was May 2017, I had an issue with it at the time. I just added to my answer recommending test bed as seen in the other answers, to not care about internal / private details. – Juan May 26 '20 at 15:25
  • To get rid of linting issues, `const spy = spyOn(component['cdRef'], 'detectChanges');` – Hary May 26 '20 at 16:53
  • @Juan, Is it possible to inject the `ChangeDetectorRef ` and check whether it is called rather than spying on the component.`ChangeDetectorRef` – Hary May 27 '20 at 10:04
  • yeah! I didn't mean to use it that way. Instead you use const cdRefMock = jasmine.createSpyObj('ChangeDetectorRef', ['detectChanges']); and then provide that one in the Test bed with useValue. Then you are injecting the spy. Don't spy on the component! I'll clarify in the edit. – Juan May 27 '20 at 15:58
  • 1
    I updated it. There's good answers out there showing the last piece using the mock, so that is as far and as detailed this update will get for now as this is an old question and answer and there's good info out there. I hope it points you in the right direction now @mbharanidharan88 – Juan May 27 '20 at 16:04
7

Not sure if this a new thing or not, but changeDetectorRef can be accessed via fixture.

See docs: https://angular.io/guide/testing#componentfixture-properties

We ran into the same issue with change detector mocking and this is ended up being the solution

FDIM
  • 1,981
  • 19
  • 21
2

Probably one point that needs to be pointed out, is that in essence here you want to test your own code, not unit test the change detector itself (which was tested by the Angular team). In my opinion this is a good indicator that you should extract the call to the change detector to a local private method (private as it is something you don't want to unit test), e.g.

private detectChanges(): void {
    this.cdRef.detectChanges();
}

Then, in your unit test, you will want to verify that your code actually called this function, and thus called the method from the ChangeDetectorRef. For example:

it('should call the change detector',
    () => {
        const spyCDR = spyOn((cmp as any).cdRef, 'detectChanges' as any);
        cmp.ngOnInit();
        expect(spyCDR).toHaveBeenCalled();
    }
);

I had the exact same situation, and this was suggested to me as a general best practice for unit testing from a senior dev who told me that unit testing is actually forcing you by this pattern to structure your code better. With the proposed restructuring, you make sure your code is flexible to change, e.g. if Angular changes the way they provide us with change detection, then you will only have to adapt the detectChanges method.

Hary
  • 5,690
  • 7
  • 42
  • 79
ArthurT
  • 358
  • 1
  • 14
  • Is it possible to inject the `ChangeDetectorRef` and check `toHaveBeenCalled` rather than spying on the `Component.ChangeDetectorRef` ? – Hary May 27 '20 at 10:08
1

For unit testing, if you are mocking ChangeDetectorRef just to satisfy dependency injection for a component to be creation, you can pass in any value.

For my case, I did this:

TestBed.configureTestingModule({
  providers: [
    FormBuilder,
    MyComponent,
    { provide: ChangeDetectorRef, useValue: {} }
  ]
}).compileComponents()
injector = getTestBed()
myComponent = injector.get(MyComponent)

It will create myComponent successfully. Just make sure test execution path does not need ChangeDetectorRef. If you do, then replace useValue: {} with a proper mock object.

In my case, I just needed to test some form creation stuff using FormBuilder.

kctang
  • 10,894
  • 8
  • 44
  • 63
0
// component
constructor(private changeDetectorRef: ChangeDetectorRef) {}

public someHandler() {
  this.changeDetectorRef.detectChanges();
}     

// spec
const changeDetectorRef = fixture.componentRef.changeDetectorRef;
jest.spyOn(changeDetectorRef, 'detectChanges');
fixture.detectChanges(); // <--- needed!!

component.someHandler();

expect(changeDetectorRef.detectChanges).toHaveBeenCalled();
0

I have seen a lot of good answers.

In 2023, with jest, I would go with :

it('detects changes', () => {
  const changeDetectorRef = fixture.changeDetectorRef; 
   
  // Spying your method.
  jest.spyOn(changeDetectorRef, 'detectChanges');

  component.someMethod(); // Which internally calls the detectChanges.

  expect(changeDetectorRef.detectChanges).toHaveBeenCalled();
});