.detectChanges() not working within Angular test

It turns out this is due to using ChangeDetectionStrategy.OnPush in the component. Using OnPush only allows you to call .detectChanges() one time, so subsequent calls will fail to do anything. I’m not familiar enough with Angular to fully understand why.

I was able to produce the required behaviour by overriding the ChangeDetectionStrategy in my TestBed configuration.

TestBed.configureTestingModule({
    imports: [],
    declarations: [TestComponent],
    providers: []
  })
    .overrideComponent(TestComponent, {
      set: { changeDetection: ChangeDetectionStrategy.Default }
    })
    .compileComponents();

Leave a Comment

tech