angular - Angular2 Unit Test Mouse Events -
i want test 1 of methods helps in closing modal window when closed outside of modal window container.
component method
public hide(): void { this.visibleanimate = false; settimeout(() => { this.visible = false; }, 200); } public onmodalclicked(event: mouseevent): void { if ((<htmlelement>event.target).classlist.contains('dialog-container')) { this.hide(); } } unit test
it('should call hide method', fakeasync(() => { component.hide(); fixture.detectchanges(); fixture.whenstable().then(() => { expect(component.visible).toequal(false); tick(200); expect(component.visibleanimate).toequal(false); }); })); it('should call onmodalclicked()', () => { const mockevent = new event('click'); --> error component.onmodalclicked(mockevent); console.log(component.visible); }); my unit test runs fine on hide() method , please let me know if doing in right way or not.
but stuck how test onmodalclicked() method because takes mouseevent parameter.
in unit testing method, event , mouseevent mismatch error occurs, obviouse biut how cover method?
it doesn't need be mouseevent, needs quack one. can make dummy object fits bill , cast mouseevent fits method parameter type. example:
function createmouseevent(hasclass, clazz): mouseevent { const event = { target: { classlist: { contains: (arg) => false } } } if (hasclass) { event.target.classlist.contains = (cls) => { expect(cls).tobe(clazz) return true } } return <any>event; } then test it, don't need test visibility. job of hide method (to change visibility). want test behavior of onmodalclicked, either calls hide or doesn't, based on element containing class. can spy on hide function, check if called.
it('onmodalclicked() should call hide() when element contains class', () => { spyon(component, 'hide') const event = createmouseevent(true, 'dialog-container'); component.onmodalclicked(event); expect(component.hide).tohavebeencalled() }) it('onmodalclicked() should not call hide() when element not contain class', () => { spyon(component, 'hide') const event = createmouseevent(false, null); component.onmodalclicked(event); expect(component.hide).not.tohavebeencalled() })
Comments
Post a Comment