I'm trying to test a code that is a part of redux-form using react-testing-library. Calling fireEvent.change for text input fields to set up new values I expect that input's values should be updated, but it never happens. Please find a fragment of the test below. Full code can be found at https://codesandbox.io/s/redux-form-simple-example-n3820 Any good examples how to test redux-form using react-testing-library?
...
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);
The problem is that you are doing fireEvent.click(submitButton) which fires a click event on the button. Your form is not listening for that event though, it's listening for the submit event on the form. You have to do this instead fireEvent.submit(formElement).
Some other things I noticed that are not necessarily wrong but could be better.
There's no need to import getByTestId you get it back from the 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')
Speaking of getByTestId you should use it as a last resort. In your case, it's much better to use getByLabelText to get the inputs and getByText to find the button. To get the form you can use getByText('Submit').closest('form').
You should use the cleanup method to avoid issues in your tests.
You have used createMockStore from redux-test-utils. It sure makes creating store easier. But the redux form should be connected to redux store to work.
You can read the documentation at:
https://redux-form.com/8.2.2/docs/gettingstarted.md/#overview and https://redux-form.com/8.2.2/docs/gettingstarted.md/#data-flow
I created the store following react-testing-library documentation to test 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>)
};
};
I too was facing the same problem as yours. So, the test I have created is different than yours but the problem here is same (i.e form is not being filled with redux-form)
Here is the link to codesandbox: https://codesandbox.io/s/nostalgic-greider-4gqcg
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With