来自文档键盘(文本,选项):
如果您只想模拟按下键盘上的按钮,则应该使用
。如果您只是想方便地将一些文本插入输入字段或文本区域,则应该使用userEvent.keyboard
。userEvent.type
尝试:
import React from 'react'
import {render, screen} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
test("the input field should take user's input", async () => {
render(<testModal />);
await userEvent.type(screen.getByTestId("add-input"), 'testTyping');
expect(inputMessage).toHaveValue("testTyping");
})
我想测试输入验证错误是否在
onChange
之后触发,但是 fireEvent.change
没有为我完成这项工作。
感谢@lin-du的回答,我能够使用
userEvent
触发错误。
但仍然不明白 fireEvent.change
是如何做到的,因为我正在组件中使用 onChange 处理错误。
it('shows error if input is greater than 50', async () => {
const user = userEvent.setup();
const { getByTestId, getByText } = render(<TestComponent />);
const inputElem = getByTestId('input-test-id');
await user.type(inputElem, '51');
const errorText = getByText('value must be less than 50.');
expect(errorText).toBeTruthy();
});