我正在尝试使用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);发布于 2019-06-16 18:14:04
问题是您正在执行在按钮上触发click事件的fireEvent.click(submitButton)。您的表单并没有侦听该事件,而是侦听表单上的submit事件。你必须这样做,而不是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方法来避免测试中出现问题。
发布于 2020-02-26 13:08:08
您已经使用了redux-test-utils中的createMockStore。这肯定会让创建商店变得更容易。但是redux form应该连接到redux store才能工作。您可以在以下位置阅读文档:
https://redux-form.com/8.2.2/docs/gettingstarted.md/#overview和https://redux-form.com/8.2.2/docs/gettingstarted.md/#data-flow
为了测试redux https://testing-library.com/docs/example-react-redux,我按照react-testing-library文档创建了这个商店
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
https://stackoverflow.com/questions/56617679
复制相似问题