如何使用react-testing-library测试redux-form

7
我正在尝试使用react-testing-library测试redux-form的一部分代码。通过调用fireEvent.change来设置新值以期望更新输入值,但是它从未发生。请在下面找到测试片段。完整代码可以在https://codesandbox.io/s/redux-form-simple-example-n3820找到。 有没有好的例子可以使用react-testing-library测试redux-form呢?
const firstNameInput = getByTestId(container, "firstName");
const lastNameInput = getByTestId(container, "lastName");

const firstName = "firstName";
const lastName = "lastName";

fireEvent.change(firstNameInput, { target: { value: firstName } });
fireEvent.change(lastNameInput, { target: { value: lastName } });

const submitButton = getByTestId(container, "submitButton");
fireEvent.click(submitButton);

expect(onSubmit).toHaveBeenCalledTimes(1);
expect(onSubmit).toHaveBeenNthCalledWith(firstName, lastName);

1
我也遇到了同样的问题。已经解决了吗? - Rojen
2个回答

5
问题在于你正在执行fireEvent.click(submitButton),这会在按钮上触发一个click事件。但是,你的表单并没有监听该事件,而是监听了表单提交事件。你需要使用fireEvent.submit(formElement)代替。
我还注意到其他一些不一定错误但可能更好的事情。
导入getByTestId是没有必要的,因为你可以从render中获取它:
// Before
import { render, getByTestId } from '@testing-library/react'
const { container } = render(<Component />)
getByTestId(container, 'foo')

// After
import { render } from '@testing-library/react'
const { getByTestId } = render(<Component />)
getByTestId('foo')

说到getByTestId,你应该把它作为最后的选择。在你的情况下,更好的方法是使用getByLabelText来获取输入框,使用getByText找到按钮。要获取form,可以使用getByText('Submit').closest('form')


在测试中,你应该使用cleanup方法,以避免出现问题。


谢谢您的回答!我已经更新了测试,使用表单提交而不是按钮点击,但仍然无法通过测试。请在此处找到更新版本 https://codesandbox.io/s/redux-form-simple-example-po8bx 看起来文本字段的值在 fireEvent.change 后没有更新。 - osmola
我认为你看到的错误与codesandbox有关 https://github.com/codesandbox/codesandbox-client/issues/502 - Gio Polvara
在本地机器上运行您的测试,您应该能够看到正确的问题。 - Gio Polvara
本地机器上的测试也失败了。 - osmola
由于fireEvent.change后输入值未更新,因此测试失败了,因此form onSubmit是使用初始输入值而不是更新后的输入值调用的。https://imgur.com/a/Q6aL7hh - osmola
@GiorgioPolvara-Gpx,您能否重新编写您的答案,因为它并没有回答问题。问题在于fireEvent.change和输入字段未更新。 - Till Kolter

3
您使用了来自redux-test-utils的createMockStore。它确实使创建store变得更容易。但是,为了使redux表单正常工作,它应该连接到redux存储器中。 您可以阅读以下文档:https://redux-form.com/8.2.2/docs/gettingstarted.md/#overviewhttps://redux-form.com/8.2.2/docs/gettingstarted.md/#data-flow 我按照react-testing-library文档创建了存储器以测试redux。https://testing-library.com/docs/example-react-redux
const renderWithRedux = (
  component,
  {
    initialState,
    store = createStore(
      combineReducers({ userReducer, form: formReducer }),
      initialState
    )
  } = {}
) => {
  return {
    ...render(<Provider store={store}>{component}</Provider>)
  };
};

我也遇到了和你一样的问题。所以,我创建的测试与你的不同,但问题是相同的(即表单不能用redux-form填充)。
这里是codesandbox的链接:https://codesandbox.io/s/nostalgic-greider-4gqcg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接