可以使用 fireEvent 方法来模拟一个实际的 DOM 事件。
示例代码:
import { fireEvent } from '@testing-library/react';
test('should simulate change event', () => {
const input = screen.getByLabelText('search');
fireEvent.change(input, { target: { value: 'react-testing-library' } });
expect(input).toHaveValue('react-testing-library');
});
在这个例子中,我们首先获取了名为'search”的 input 元素,并且使用 fireEvent.change 方法来模拟输入'react-testing-library”的操作。然后,我们检查输入元素的值是否正确。