javascript - React 测试库:使用 getBy* 查找元素的第一次出现
问题描述
我的组件有两个相似的表单(两个带有用户名/密码字段的表单)和两个Submit
带有“提交”文本的按钮。为了测试提交处理程序,我正在模拟表单字段的类型事件,然后单击提交按钮,如下所示:
it('test submit handler', async () => {
const myProvider = ({children}) => <Provider store={store}>{children}</Provider>;
render(<MyComponent />, {wrapper: myProvider});
expect(await screen.findByText('username')).toBeTruthy();
expect(await screen.findByText('password')).toBeTruthy();
await userEvent.type(screen.getByLabelText('username'), 'someusername');
await userEvent.type(screen.getByLabelText('password'), 'somepassword');
fireEvent.click(screen.getByText('Submit'));
await waitFor(() => expect(onSubmit).toBeCalledTimes(1));
});
});
这样做会导致错误TestingLibraryElementError: Found multiple elements with the text: Submit
。我查找了这些getBy*
方法的文档,看起来它们解释了找到的第一个元素,或者如果有多个,它们会抛出一个错误,这就是这里发生的事情。这两种形式具有不同的处理函数,我想测试这两个函数是否在提交时被调用。什么是访问此Submit
按钮第一次出现的好方法?
我尝试用getByText
with替换,findByText
但这会导致返回 a Promise { <pending> }
, await 会导致上述相同的TestingLibraryElementError
错误。
解决方案
推荐阅读
- postgresql - 重复对 PostgreSQL 数据库的耗时查询
- amazon-web-services - AWS 批处理无法运行 Fargate 容器
- spring - 在 Spring Boot 中通过 NTLM 和 Feign Client 进行身份验证
- mysql - AWS EC2 问题:mysql 无法与我的烧瓶应用程序上的 sqlalchemy 连接
- google-apps-script - 尽管触发器已被删除,但 Apps 脚本触发器功能仍在运行
- python - 我是 tkinter 的新手......为什么当我滚动时这些条目没有移动?
- java - 无法让我的 SQL 更新我通过它传递的更改
- javascript - SVG 上的 D3 突然线性渐变变化在 Chrome 中不起作用
- python - 为什么 gmail 拒绝我的 SMTP 连接?
- mysql - 我想插入加入日期和当前日期之间的差异(以年为单位)并将其添加到每一行的新列中