49 lines
1.5 KiB
TypeScript
49 lines
1.5 KiB
TypeScript
import { render, screen, fireEvent } from '@testing-library/react';
|
|
import { vi, test, expect, beforeEach, afterEach } from 'vitest';
|
|
import SearchBar from '../../src/components/SearchBar';
|
|
import { search } from '../../src/api/client';
|
|
|
|
vi.mock('../../src/api/client');
|
|
|
|
beforeEach(() => {
|
|
vi.mocked(search).mockReset();
|
|
vi.useFakeTimers();
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
test('debounces input for 300ms before calling search', async () => {
|
|
vi.mocked(search).mockResolvedValue({ results: [] });
|
|
const onQueryChange = vi.fn();
|
|
const onResults = vi.fn();
|
|
|
|
render(<SearchBar onQueryChange={onQueryChange} onResults={onResults} />);
|
|
|
|
const input = screen.getByRole('textbox') as HTMLInputElement;
|
|
fireEvent.change(input, { target: { value: '检索' } });
|
|
|
|
expect(onQueryChange).toHaveBeenLastCalledWith('检索');
|
|
expect(search).not.toHaveBeenCalled();
|
|
|
|
vi.advanceTimersByTime(300);
|
|
|
|
expect(search).toHaveBeenCalledWith('检索');
|
|
});
|
|
|
|
test('clearing the input immediately reports empty results without calling search', async () => {
|
|
vi.mocked(search).mockResolvedValue({ results: [] });
|
|
const onQueryChange = vi.fn();
|
|
const onResults = vi.fn();
|
|
|
|
render(<SearchBar onQueryChange={onQueryChange} onResults={onResults} />);
|
|
|
|
const input = screen.getByRole('textbox') as HTMLInputElement;
|
|
fireEvent.change(input, { target: { value: 'x' } });
|
|
vi.advanceTimersByTime(300);
|
|
fireEvent.change(input, { target: { value: '' } });
|
|
|
|
expect(onResults).toHaveBeenCalledWith([]);
|
|
});
|