Skip to content

Instantly share code, notes, and snippets.

@7jpsan
Created September 5, 2019 19:09
Show Gist options
  • Select an option

  • Save 7jpsan/5ac270f19c5d8d715220c06f6ccd123a to your computer and use it in GitHub Desktop.

Select an option

Save 7jpsan/5ac270f19c5d8d715220c06f6ccd123a to your computer and use it in GitHub Desktop.
Runs Angular 7 change detection when the component uses onPush strategy
import { ChangeDetectorRef } from '@angular/core';
import { ComponentFixture } from '@angular/core/testing';
export async function runOnPushChangeDetection<T>(cf: ComponentFixture<T>) {
const cd = cf.debugElement.injector.get<ChangeDetectorRef>(
// tslint:disable-next-line:no-any
ChangeDetectorRef as any
);
cd.detectChanges();
await cf.whenStable();
return;
}
// To be used in tests like this:
import { runOnPushChangeDetection } from "../../testing-helper/run-on-push-change-detection";
let mockService: jasmine.SpyObj<MockService>;
beforeEach(async(() => {
//... mocks setup ...
TestBed.configureTestingModule({
declarations: [ComponentBeingTested],
providers: [{ provide: SomeService, useValue: mockService }]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ComponentBeingTested);
component = fixture.componentInstance;
// let it run the first detectChange anyway... All good!!
fixture.detectChanges();
});
it('should render a checkbox matching the model (true) and update it', async () => {
// Bind some inputs
component.record = { id: 'some-value', selected: true };
// Magic happens here.
await runOnPushChangeDetection(fixture);
const elWithDirective = fixture.debugElement.query(
By.directive(MatCheckbox)
);
const instance = elWithDirective.injector.get(MatCheckbox);
expect(instance.checked).toBe(true);
// Change to false
component.record.selected = false;
// Can run multiple times
await runOnPushChangeDetection(fixture);
expect(instance.checked).toBe(false);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment