React测试库userEvent.只能识别第一个字母的输入



我使用"@testing-library/user-event"; "^14.2.0"12.

这是我的测试

it('test search input', async () => {
const searchInput = screen.getByPlaceholderText('Search assets');
expect(searchInput).toBeInTheDocument();
await userEvent.type(searchInput, 'test{Enter}');
expect(searchInput).toHaveValue('test');

测试失败,错误如下

expect(element).toHaveValue(test)
Expected the element to have value:
test
Received:
t
195 |
196 |     await userEvent.type(searchInput, 'test{Enter}');
> 197 |     expect(searchInput).toHaveValue('test');
|                         ^
198 |   });
199 | });
200 |

更新:这是我的组件代码。组件是非常简单的输入框与onKeyDown事件。

const SearchBox = () => {
const router = useRouter();
const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
const element = event.currentTarget as HTMLInputElement;
const searchText = element.value;
if (event.key === 'Enter') {
router.push({
pathname: '/search',
query: { q: searchText },
});
}
};
return (
<>
<input
className={styles.searchInput}
type="text"
placeholder="Search assets"
onKeyDown={handleKeyDown}
/>
</>
);
};

export default SearchBox;

有人能帮帮我吗?

您可以从RTL导入waitFor,然后稍后使用它来验证输入的值。

import { screen, waitFor } from "@testing-library/react";

const inputField = screen.getByLabelText(label);
userEvent.type(inputField, data);
await waitFor(() => expect(inputField).toHaveValue(data));

相关内容

  • 没有找到相关文章

最新更新