|
| 1 | +/* global hotkey */ |
| 2 | + |
| 3 | +let buttonsClicked = [] |
| 4 | +function buttonClickHandler(event) { |
| 5 | + buttonsClicked.push(event.target.id) |
| 6 | +} |
| 7 | + |
| 8 | +describe('hotkey', function() { |
| 9 | + beforeEach(function() { |
| 10 | + document.body.innerHTML = ` |
| 11 | + <button id="button1" data-hotkey="b">Button 1</button> |
| 12 | + <button id="button2">Button 2</button> |
| 13 | + <button id="button3" data-hotkey="Control+b">Button 3</button> |
| 14 | + <input id="textfield" /> |
| 15 | + ` |
| 16 | + for (const button of document.querySelectorAll('button')) { |
| 17 | + button.addEventListener('click', buttonClickHandler) |
| 18 | + } |
| 19 | + for (const button of document.querySelectorAll('[data-hotkey]')) { |
| 20 | + hotkey.install(button) |
| 21 | + } |
| 22 | + }) |
| 23 | + |
| 24 | + afterEach(function() { |
| 25 | + for (const button of document.querySelectorAll('button')) { |
| 26 | + button.removeEventListener('click', buttonClickHandler) |
| 27 | + } |
| 28 | + for (const button of document.querySelectorAll('[data-hotkey]')) { |
| 29 | + hotkey.uninstall(button) |
| 30 | + } |
| 31 | + document.body.innerHTML = '' |
| 32 | + buttonsClicked = [] |
| 33 | + }) |
| 34 | + |
| 35 | + it('triggers buttons that have `data-hotkey` as a attribute', function() { |
| 36 | + document.dispatchEvent(new KeyboardEvent('keydown', {key: 'b'})) |
| 37 | + assert.include(buttonsClicked, 'button1') |
| 38 | + }) |
| 39 | + |
| 40 | + it("doesn't trigger buttons that don't have `data-hotkey` as a attribute", function() { |
| 41 | + document.dispatchEvent(new KeyboardEvent('keydown', {key: 'b'})) |
| 42 | + assert.notInclude(buttonsClicked, 'button2') |
| 43 | + }) |
| 44 | + |
| 45 | + it("doesn't trigger when user is focused on a form field", function() { |
| 46 | + document.getElementById('textfield').dispatchEvent(new KeyboardEvent('keydown', {key: 'b'})) |
| 47 | + assert.deepEqual(buttonsClicked, []) |
| 48 | + }) |
| 49 | + |
| 50 | + it('handles multiple keys in a hotkey combination', function() { |
| 51 | + document.dispatchEvent(new KeyboardEvent('keydown', {key: 'b', ctrlKey: true})) |
| 52 | + assert.include(buttonsClicked, 'button3') |
| 53 | + }) |
| 54 | + |
| 55 | + it("doesn't trigger elements where the hotkey library has been uninstalled", function() { |
| 56 | + hotkey.uninstall(document.querySelector('#button1')) |
| 57 | + document.dispatchEvent(new KeyboardEvent('keydown', {key: 'b'})) |
| 58 | + assert.deepEqual(buttonsClicked, []) |
| 59 | + }) |
| 60 | +}) |
0 commit comments