|
| 1 | +import type { Ref } from 'vue' |
| 2 | +import { beforeEach, describe, expect, it, vi } from 'vitest' |
| 3 | +import { shallowRef } from 'vue' |
| 4 | +import { onStartTyping } from './index' |
| 5 | + |
| 6 | +describe('onStartTyping', () => { |
| 7 | + let element: Ref<HTMLInputElement> |
| 8 | + let callBackFn: any |
| 9 | + |
| 10 | + beforeEach(() => { |
| 11 | + element = shallowRef(document.createElement('input')) |
| 12 | + element.value.tabIndex = 1 |
| 13 | + callBackFn = vi.fn() |
| 14 | + }) |
| 15 | + |
| 16 | + function dispatchKeyDownEvent(keyCode: number) { |
| 17 | + const ev = new KeyboardEvent('keydown', { keyCode }) |
| 18 | + document.dispatchEvent(ev) |
| 19 | + } |
| 20 | + |
| 21 | + function range(size: number, startAt = 0) { |
| 22 | + return [...Array.from({ length: size }).keys()].map(i => i + startAt) |
| 23 | + } |
| 24 | + |
| 25 | + it('triggers callback with any letter', () => { |
| 26 | + const letters = range(26, 65) |
| 27 | + |
| 28 | + onStartTyping(callBackFn) |
| 29 | + |
| 30 | + letters.forEach((letter) => { |
| 31 | + document.body.focus() |
| 32 | + dispatchKeyDownEvent(letter) |
| 33 | + }) |
| 34 | + |
| 35 | + expect(callBackFn).toBeCalledTimes(letters.length) |
| 36 | + }) |
| 37 | + |
| 38 | + it('triggers callback with any number', () => { |
| 39 | + const numbers = range(10, 48) |
| 40 | + const numpadNumbers = range(10, 96) |
| 41 | + |
| 42 | + onStartTyping(callBackFn) |
| 43 | + |
| 44 | + numbers.forEach((number) => { |
| 45 | + document.body.focus() |
| 46 | + dispatchKeyDownEvent(number) |
| 47 | + }) |
| 48 | + |
| 49 | + numpadNumbers.forEach((number) => { |
| 50 | + document.body.focus() |
| 51 | + dispatchKeyDownEvent(number) |
| 52 | + }) |
| 53 | + |
| 54 | + expect(callBackFn).toBeCalledTimes(numbers.length + numpadNumbers.length) |
| 55 | + }) |
| 56 | + |
| 57 | + it('does not trigger callback with invalid characters', () => { |
| 58 | + const arrows = range(4, 37) |
| 59 | + const functionKeys = range(32, 112) |
| 60 | + |
| 61 | + onStartTyping(callBackFn) |
| 62 | + |
| 63 | + arrows.forEach((arrow) => { |
| 64 | + document.body.focus() |
| 65 | + dispatchKeyDownEvent(arrow) |
| 66 | + }) |
| 67 | + |
| 68 | + functionKeys.forEach((functionKey) => { |
| 69 | + document.body.focus() |
| 70 | + dispatchKeyDownEvent(functionKey) |
| 71 | + }) |
| 72 | + |
| 73 | + expect(callBackFn).toBeCalledTimes(0) |
| 74 | + }) |
| 75 | +}) |
0 commit comments