27
loading...
This website collects cookies to deliver better user experience
<Provider>
you use to wrap your tests and then return it. For example:import { render } from "@testing-library/react";
import { store } from "../app/store";
function renderWithContext(element) {
render(
<Provider store={store}>{element}</Provider>
);
return { store };
}
test("table should render all kinds of data", () => {
const { store } = renderWithContext(<ResultsTable />);
// expect() table to be empty
store.dispatch({ type: "POPULATE_DATA", data: { /* ... */ })
// expect() table to be full
});
test("counter should update count", () => {
const { store } = renderWithContext(<CounterButton />);
expect(store.getState().count).toEqual(0);
userEvent.click(screen.getByRole("button"));
expect(store.getState().count).toEqual(1);
});
getStoreWithState
method I showed in my previous article as a key utility.// ...
export const store = configureStore({ reducer });
export function getStoreWithState(preloadedState) {
return configureStore({ reducer, preloadedState });
}
preloadedState
option, which lets us render components in tests with state already setup in a specific way (similar to mock redux store). The second and more subtle accomplishment here is that we're giving our generated store access to the same reducers used by our app's store. This gives us an isolated store to use for each test that also has access to the full power of our application's reducers.