Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Let's make your life better testing Angular like writing jQuery code. It's inspired by https://github.com/airbnb/enzyme.
describe('Component', () => {
let wrapper;
beforeEach(() => {
wrapper = build(Component);
wrapper.set({
data: 'value',
});
});
it('should include data', () => {
expect(wrapper.text).toMatch('value');
});
});
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
function createWrapper(fixture, debugElements) {
const debugElement = debugElements[0];
return {
get fixture() {
return fixture;
},
detectChanges() {
fixture.detectChanges();
return this;
},
get debugElement() {
return debugElement;
},
get component() {
// ensure the current element is the host of a component
if (debugElement && this.element === debugElement._debugContext.componentRenderElement) {
return debugElement.componentInstance;
}
},
instance(token) {
return debugElement.injector.get(token);
},
get element() {
return debugElement && debugElement.nativeElement;
},
get text(): string {
return this.element.textContent;
},
get length(): number {
return debugElements.length;
},
attr(attribute) {
return this.element.getAttribute(attribute);
},
hasClass(className): boolean {
return this.element.classList.contains(className);
},
simulate(eventNameOrObject, options = {}) {
if (typeof eventNameOrObject === 'object') {
this.element.dispatchEvent(eventNameOrObject);
} else {
this.element.dispatchEvent(new Event(eventNameOrObject, options));
}
this.detectChanges();
return this;
},
at(index) {
return createWrapper(fixture, [debugElements[index]]);
},
find(selector) {
return createWrapper(fixture,
debugElement.queryAll(By.css(selector)));
},
get(property) {
if (this.component) {
return this.component[property];
}
return this.element[property];
},
set(properties) {
if (this.component) {
Object.assign(this.component, properties);
this.detectChanges();
} else {
Object.assign(this.element, properties);
}
return this;
},
}
}
export function build(component) {
const fixture = TestBed.createComponent(component);
fixture.detectChanges();
return createWrapper(fixture, [fixture.debugElement]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.