|
| 1 | +import { describe, expect, test, vi } from 'vitest' |
| 2 | +import { createServer } from '../server' |
| 3 | +import { preview } from '../preview' |
| 4 | +import { bindCLIShortcuts } from '../shortcuts' |
| 5 | + |
| 6 | +describe('bindCLIShortcuts', () => { |
| 7 | + test.each([ |
| 8 | + ['dev server', () => createServer()], |
| 9 | + ['preview server', () => preview()], |
| 10 | + ])('binding custom shortcuts with the %s', async (_, startServer) => { |
| 11 | + const server = await startServer() |
| 12 | + |
| 13 | + try { |
| 14 | + const xAction = vi.fn() |
| 15 | + const yAction = vi.fn() |
| 16 | + |
| 17 | + bindCLIShortcuts( |
| 18 | + server, |
| 19 | + { |
| 20 | + customShortcuts: [ |
| 21 | + { key: 'x', description: 'test x', action: xAction }, |
| 22 | + { key: 'y', description: 'test y', action: yAction }, |
| 23 | + ], |
| 24 | + }, |
| 25 | + true, |
| 26 | + ) |
| 27 | + |
| 28 | + expect.assert( |
| 29 | + server._rl, |
| 30 | + 'The readline interface should be defined after binding shortcuts.', |
| 31 | + ) |
| 32 | + expect(xAction).not.toHaveBeenCalled() |
| 33 | + |
| 34 | + server._rl.emit('line', 'x') |
| 35 | + await vi.waitFor(() => expect(xAction).toHaveBeenCalledOnce()) |
| 36 | + |
| 37 | + const xUpdatedAction = vi.fn() |
| 38 | + const zAction = vi.fn() |
| 39 | + |
| 40 | + xAction.mockClear() |
| 41 | + bindCLIShortcuts( |
| 42 | + server, |
| 43 | + { |
| 44 | + customShortcuts: [ |
| 45 | + { key: 'x', description: 'test x updated', action: xUpdatedAction }, |
| 46 | + { key: 'z', description: 'test z', action: zAction }, |
| 47 | + ], |
| 48 | + }, |
| 49 | + true, |
| 50 | + ) |
| 51 | + |
| 52 | + expect(xUpdatedAction).not.toHaveBeenCalled() |
| 53 | + server._rl.emit('line', 'x') |
| 54 | + await vi.waitFor(() => expect(xUpdatedAction).toHaveBeenCalledOnce()) |
| 55 | + |
| 56 | + // Ensure original xAction is not called again |
| 57 | + expect(xAction).not.toBeCalled() |
| 58 | + |
| 59 | + expect(yAction).not.toHaveBeenCalled() |
| 60 | + server._rl.emit('line', 'y') |
| 61 | + await vi.waitFor(() => expect(yAction).toHaveBeenCalledOnce()) |
| 62 | + |
| 63 | + expect(zAction).not.toHaveBeenCalled() |
| 64 | + server._rl.emit('line', 'z') |
| 65 | + await vi.waitFor(() => expect(zAction).toHaveBeenCalledOnce()) |
| 66 | + } finally { |
| 67 | + await server.close() |
| 68 | + } |
| 69 | + }) |
| 70 | +}) |
0 commit comments