Angular 2 testing directives with events bound to document
I ran into an issue today where I was writing a test for a directive I created. The directive has a HostListener
which binds to document:mouseup
and the tests were not able to trigger that particular event with the typical triggerEventHandler
function. There is currently a feature request to help with this issue. The workaround stated on that feature request wasn't very descriptive, so I had to figure out another way to call the bound event listener on my directive. Here's some code:
@Component({
template: '<div myDirective>'
})
class TestComponent implements OnInit {
// Here is how to get access directly to your directive from your test component.
@ViewChild(MyDirective) directive: MyDirective;
constructor() { }
ngOnInit() { }
}
describe('MyDirectiveTest', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ TestComponent, MyDirective ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should organize the tabs', () => {
// Now we can use that directive and call the method that was bound to document:mouseup
component.directive.onMouseUp({ pageX: 10, pageY: 20 });
// expect tests below...
});
});