|
1 | | -import { describe, it, expect, expectTypeOf } from 'vitest'; |
| 1 | +import { describe, it, expect, expectTypeOf, vi } from 'vitest'; |
2 | 2 | import { render } from '@inquirer/testing'; |
| 3 | +import { withResolver } from '@inquirer/type'; |
3 | 4 | import search, { Separator } from './src/index.ts'; |
4 | 5 |
|
5 | 6 | // Array of all countries names as string |
@@ -39,6 +40,52 @@ function getListSearch( |
39 | 40 | } |
40 | 41 |
|
41 | 42 | describe('search prompt', () => { |
| 43 | + it('does not submit stale choices and keeps the search term while a search is pending', async () => { |
| 44 | + const { promise: resultsPromise, resolve: resolveResults } = |
| 45 | + withResolver<Array<string>>(); |
| 46 | + const terms: Array<string | undefined> = []; |
| 47 | + const { answer, events, nextRender } = await render(search, { |
| 48 | + message: 'Select a Canadian province', |
| 49 | + source: (term: string | undefined) => { |
| 50 | + terms.push(term); |
| 51 | + return term ? resultsPromise : ['Alberta']; |
| 52 | + }, |
| 53 | + }); |
| 54 | + |
| 55 | + // A first enter while the search for "Que" is still pending must not |
| 56 | + // submit any stale choice. |
| 57 | + events.type('Que'); |
| 58 | + await nextRender(); |
| 59 | + events.keypress('enter'); |
| 60 | + |
| 61 | + // The search term must survive the enter keypress. |
| 62 | + events.type('bec'); |
| 63 | + await nextRender(); |
| 64 | + |
| 65 | + resolveResults(['Quebec']); |
| 66 | + await nextRender(); |
| 67 | + events.keypress('enter'); |
| 68 | + await expect(answer).resolves.toEqual('Quebec'); |
| 69 | + expect(terms.at(-1)).toBe('Quebec'); |
| 70 | + }); |
| 71 | + |
| 72 | + it('does not start another validation while one is pending', async () => { |
| 73 | + const { promise: validation, resolve: resolveValidation } = withResolver<boolean>(); |
| 74 | + const validate = vi.fn(() => validation); |
| 75 | + const { answer, events } = await render(search, { |
| 76 | + message: 'Select a Canadian province', |
| 77 | + source: () => ['Quebec'], |
| 78 | + validate, |
| 79 | + }); |
| 80 | + |
| 81 | + events.keypress('enter'); |
| 82 | + events.keypress('enter'); |
| 83 | + resolveValidation(true); |
| 84 | + |
| 85 | + await expect(answer).resolves.toEqual('Quebec'); |
| 86 | + expect(validate).toHaveBeenCalledOnce(); |
| 87 | + }); |
| 88 | + |
42 | 89 | it('allows to search', async () => { |
43 | 90 | const { answer, events, getScreen, nextRender } = await render(search, { |
44 | 91 | message: 'Select a Canadian province', |
|
0 commit comments