Skip to content

Instantly share code, notes, and snippets.

@michaelbromley
Created February 22, 2018 15:26
Show Gist options
  • Save michaelbromley/bf2c93d57cb7d280ab90e8596dfb7423 to your computer and use it in GitHub Desktop.
Save michaelbromley/bf2c93d57cb7d280ab90e8596dfb7423 to your computer and use it in GitHub Desktop.
Angular MockComponent Decorator
import 'Component, EventEmitter, Input, Output' from '@angular/core';
@Component({
selector: 'foo',
template: `<button (dblclick)="onDoubleClick($event)">{{ label }}</button>`
})
export class FooComponent {
@Input label = 'Double Click Me!';
@Output doubleClick = new EventEmitter();
onDoubleClick(e) {
this.doubleClick.emit(e);
}
}
import 'Component' from '@angular/core';
import 'FooComponent' from './foo.component';
function MockComponent(config?: Component & { template: string; selector: string }) {
return target => {
const mockName = target.prototype.constructor.name;
for (const prop in target.prototype) {
if (prop !== 'constructor') {
target.prototype[prop] = jasmine.createSpy(`${mockName}#${prop}`).and.callThrough();
}
}
return config ? Component(config)(target) : target;
};
}
// Create a mock which wraps all methods in a Jasmine spy
@MockComponent()
class MockFooComponent extends FooComponent {}
// Can also override the metadata of the original
@MockComponent({
selector: 'foo',
template: 'some mock template'
})
class MockFooComponent2 extends FooComponent {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment