Skip to content

Instantly share code, notes, and snippets.

@kroeder
Created November 12, 2019 08:57
Show Gist options
  • Save kroeder/0130e04294cd5e4a791e5c4e20797085 to your computer and use it in GitHub Desktop.
Save kroeder/0130e04294cd5e4a791e5c4e20797085 to your computer and use it in GitHub Desktop.
Test util for setting component properties and call ngOnChanges with these changes
export class TypedSimpleChange<T> {
constructor(public previousValue: T | undefined, public currentValue: T, public firstChange: boolean) {};
}
declare type TypedSimpleChanges<T> = {
[Key in keyof T]?: TypedSimpleChange<T[Key]>;
};
function updatePropsAndCallNgOnChanges<T extends object>(componentFixture: OnChanges, changes: TypedSimpleChanges<Partial<T>>) {
const simpleChanges: SimpleChanges = {};
for (const key in changes) {
if (changes.hasOwnProperty(key)) {
const change = changes[key] as SimpleChange;
(componentFixture as any)[key] = change.currentValue;
simpleChanges[key] = new SimpleChange(change.previousValue, change.currentValue, change.firstChange);
}
}
componentFixture.ngOnChanges(simpleChanges);
}
@kroeder
Copy link
Author

kroeder commented Nov 12, 2019

describe('SomeComponent', () => {
    let component: SomeComponent;
    let fixture: ComponentFixture<SomeComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [SomeComponent]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(SomeComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    // now
    it('should change some component props and call ngOnChanges', () => {

        updatePropsAndCallNgOnChanges<SomeComponent>(component, {
            propA: new TypedSimpleChange(undefined, 'foo', true),
            propB: new TypedSimpleChange(undefined, 'bar', true),
            propC: new TypedSimpleChange(undefined, 'baz', true)
        })

        expect(component.getSomething()).toEqual({ /* ... */ })
    });

    // previously
    it('should change some component props and call ngOnChanges', () => {

        component.propA = 'foo';
        component.propB = 'bar';
        component.propC = 'baz';
        component.ngOnChanges({
            propA: new SimpleChange(undefined, component.propA, true),
            propB: new SimpleChange(undefined, component.propB, true),
            propC: new SimpleChange(undefined, component.propC, true)
        })

        expect(component.getSomething()).toEqual({ /* ... */ })
    });
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment