I'm using Redux to manage the state for my components. While it works on my application, I cannot get it to work within my react-testing-library testing suite.
Good news is, Redux-RTK has documentation for setting up their library with react-testing-library here (example shown below). Bad news is, I'm having difficulty converting it from jsx to tsx and doing whatever else needs to be done to get it to actually work within the tests.
redux docs
this is the wrapper they provide to give components (within tests) access to ... the redux store/behaviors?
// testing-utils.ts
import React from 'react'
import { render as rtlRender } from '@testing-library/react'
import { configureStore } from '@reduxjs/toolkit'
import { Provider } from 'react-redux'
// Import your own reducer
import alertReducer from '../alertSlice'
function render(
ui,
{
preloadedState,
store = configureStore({
reducer: { alert: alertReducer },
preloadedState,
}),
...renderOptions
} = {}
) {
function Wrapper({ children }) {
return <Provider store={store}>{children}</Provider>
}
return rtlRender(ui, { wrapper: Wrapper, ...renderOptions })
}
// re-export everything
export * from '@testing-library/react'
// override render method
export { render }
- when I write a test in
react-testing-library, ie user clicks a button, the value I'm testing for (shown below) appears as "undefined".
import { render, screen } from "../../../testing-utils/test-utils";
test.only("when the user clicks the 'click me' button, a snackbar appears", async () => {
expect(screen.queryByText(/header/i)).toBeInTheDocument();
const clickMeButton = screen.getByRole("button", { name: /click me/i });
user.click(clickMeButton);
expect(
// screen.debug() shows: 'undefined header' not ... 'great job header'
await screen.findByText(/great job header/i)
).toBeInTheDocument();
});
- component I'm testing against:
const SelectMedia = () => {
const alertState = useAppSelector(selectAlert);
const dispatch = useAppDispatch();
const createSnackBar = () => {
dispatch(
setAlert({
type: "success",
message: "great job",
display: "support-both",
})
);
};
return (
<SelectMediaWrapper>
{alertState && alertState.message + " header"}
// in tests, returns as "undefined header"
</SelectMediaWrapper>
)
}
I'm not sure where to take it from here, the testing-utils solution is based very close to the docs and my behaviors are very similar to what they used in the redux resource. However, I can't seem to get it to work and I'm not sure what I am missing in my implementation. Any thoughts?