@testing-library/user-event
模拟用户在
<input>
要素第二,你会想嘲笑我
useProducts
实现来声明它在测试中被正确调用。
import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import SearchBar from '<path-to-search-bar-component>'; // Update this accordingly
import * as hooks from '<path-to-hooks-file>'; // Update this accordingly
describe('Test <SearchBar />', () => {
it('should call useProducts after 300ms after typing', async () => {
const mockHook = jest.fn();
jest.spyOn(hooks, 'useProducts').mockImplementation(mockHook);
render(<SearchBar />);
const input = screen.getByPlaceholderText('Search for brands or shoes...');
userEvent.type(input, 'A');
expect(mockHook).not.toHaveBeenCalledWith('A'); // It won't be called immediately
await waitFor(() => expect(mockHook).toHaveBeenCalledWith('A'), { timeout: 350 }); // But will get called within 350ms
jest.clearAllMocks();
});
});