我正在尝试使用 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);
最佳答案
问题是你在做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
避免测试中出现问题的方法。
关于redux-form - 如何使用 react-testing-library 测试 redux-form,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56617679/