首页 > 解决方案 > 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按钮第一次出现的好方法?

我尝试用getByTextwith替换,findByText但这会导致返回 a Promise { <pending> }, await 会导致上述相同的TestingLibraryElementError错误。

标签: javascriptreactjsunit-testingreact-testing-library

解决方案


推荐阅读