Skip to content

Instantly share code, notes, and snippets.

@GregOnNet
Created July 18, 2019 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GregOnNet/c86febd2fbb1ba5ccccf794a68a55112 to your computer and use it in GitHub Desktop.
Save GregOnNet/c86febd2fbb1ba5ccccf794a68a55112 to your computer and use it in GitHub Desktop.
Component Object simplifying testing for Angular Components
import { ComponentFixture } from '@angular/core/testing';
import { Predicate, DebugElement } from '@angular/core';
import { ValueSetter } from '../company-create/company-create.component.spec.co';
export class ComponentObject<T> {
constructor(private fixture: ComponentFixture<T>) {}
get componentInstance(): T {
return this.fixture.componentInstance;
}
detectChanges() {
this.fixture.detectChanges();
}
query<TElement>(selector: Predicate<DebugElement>): TElement {
return this.fixture.debugElement.query(selector).nativeElement;
}
queryAll<TElement>(selector: Predicate<DebugElement>): TElement[] {
return this.fixture.debugElement.queryAll(selector).map(element => element.nativeElement);
}
protected bindInput(selector: Predicate<DebugElement>): HTMLInputElement & ValueSetter {
const input = this.query<HTMLInputElement>(selector);
const setValue = (value: string) => {
input.value = value;
input.dispatchEvent(new Event('input'));
this.detectChanges();
};
return Object.assign(input, { setValue });
}
protected bindButton(selector: Predicate<DebugElement>): HTMLButtonElement {
const button = this.query<HTMLButtonElement>(selector);
button.addEventListener('click', () => this.detectChanges);
return button;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment