Created
February 22, 2018 15:26
-
-
Save michaelbromley/bf2c93d57cb7d280ab90e8596dfb7423 to your computer and use it in GitHub Desktop.
Angular MockComponent Decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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