![](/img/trans.png)
[英]React Testing | importing userEvent from '@testing-library/user-event' generates error "toBeInTheDocument is not a function"
[英]How can I test `onKeyDown` prop in React with @testing-library/user-event version 14?
我正在使用 React 创建菜单项列表。 我想测试当用户单击或按下某个项目上的 enter 时,将调用onSelect
道具。
这是我的组件的简化版本:
import React from "react";
export const Item = ({ children, onSelect }) => {
const onKeyDown = ({ keyCode }) => keyCode === 13 && onSelect();
return (
<div onClick={onSelect} onKeyDown={onKeyDown} tabIndex={0}>
{children}
</div>
);
};
这是我的测试:
describe("Item", () => {
it("calls onSelect when user clicks on the item or presses Enter", async () => {
const user = userEvent.setup()
const onSelect = jest.fn();
const children = "Settings";
render(<Item onSelect={onSelect}>{children}</Item>);
const item = screen.getByText(children);
await user.click(item);
expect(onSelect).toHaveBeenCalledTimes(1);
await user.pointer({target: item, keys: '[Enter]'})
expect(onSelect).toHaveBeenCalledTimes(2);
});
});
运行测试时,我得到以下 output:
Item › calls onSelect when user clicks on the item or presses Enter
expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 2
Received number of calls: 1
48 |
49 | await user.pointer({target: item, keys: '[Enter]'})
> 50 | expect(onSelect).toHaveBeenCalledTimes(2);
| ^
51 | });
52 | });
53 |
当用户在项目组件上按 Enter 时,如何测试调用了onSelect
?
来自文档
fireEvent.keyDown(domNode, {key: 'Enter', code: 'Enter', charCode: 13})
fireEvent.keyDown(domNode, {key: 'A', code: 'KeyA'})
https://testing-library.com/docs/user-event/keyboard
keyboard
API 允许模拟与键盘的交互。 它接受描述关键操作的string
。
await user.keyboard('[Enter]')
KeyboardEvent.keyCode
已弃用。
因此,我们不支持它并鼓励您更新您的实现以使用未弃用的功能,如KeyboardEvent.key
或KeyboardEvent.code
。
https://codesandbox.io/s/crazy-snyder-gurptu?file=/src/Item.test.js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.