|
| 1 | +import { mount } from 'enzyme'; |
| 2 | +import { useRef } from 'preact/hooks'; |
| 3 | +import { act } from 'preact/test-utils'; |
| 4 | + |
| 5 | +import { useClickAway } from '../use-click-away'; |
| 6 | + |
| 7 | +describe('useClickAway', () => { |
| 8 | + let handler; |
| 9 | + |
| 10 | + const events = [new Event('mousedown'), new Event('click')]; |
| 11 | + |
| 12 | + // Create a fake component to mount in tests that uses the hook |
| 13 | + function FakeComponent({ enabled = true }) { |
| 14 | + const myRef = useRef(); |
| 15 | + useClickAway(myRef, handler, { enabled }); |
| 16 | + return ( |
| 17 | + <div ref={myRef}> |
| 18 | + <button>Hi</button> |
| 19 | + </div> |
| 20 | + ); |
| 21 | + } |
| 22 | + |
| 23 | + function createComponent(props) { |
| 24 | + return mount(<FakeComponent {...props} />); |
| 25 | + } |
| 26 | + |
| 27 | + beforeEach(() => { |
| 28 | + handler = sinon.stub(); |
| 29 | + }); |
| 30 | + |
| 31 | + events.forEach(event => { |
| 32 | + it(`should invoke callback once for events outside of element (${event.type})`, () => { |
| 33 | + const wrapper = createComponent(); |
| 34 | + |
| 35 | + act(() => { |
| 36 | + document.body.dispatchEvent(event); |
| 37 | + }); |
| 38 | + wrapper.update(); |
| 39 | + |
| 40 | + assert.calledOnce(handler); |
| 41 | + |
| 42 | + wrapper.setProps({ enabled: false }); |
| 43 | + |
| 44 | + act(() => { |
| 45 | + document.body.dispatchEvent(event); |
| 46 | + }); |
| 47 | + |
| 48 | + // Cleanup of hook should have removed eventListeners, so the callback |
| 49 | + // is not called again |
| 50 | + assert.calledOnce(handler); |
| 51 | + }); |
| 52 | + }); |
| 53 | + |
| 54 | + events.forEach(event => { |
| 55 | + it(`should not invoke callback on events inside of container (${event.type})`, () => { |
| 56 | + const wrapper = createComponent(); |
| 57 | + const button = wrapper.find('button'); |
| 58 | + |
| 59 | + act(() => { |
| 60 | + button.getDOMNode().dispatchEvent(event); |
| 61 | + }); |
| 62 | + wrapper.update(); |
| 63 | + |
| 64 | + assert.equal(handler.callCount, 0); |
| 65 | + }); |
| 66 | + }); |
| 67 | +}); |
0 commit comments