DEV Community

Discussion on: Mocking redux useSelector-hook

 
fredrikbergqvist profile image
Fredrik Bergqvist

It does not seem like redux is being mocked (looking for mockImplementation in react redux)

In the code below I've listed all moving parts of the test

  1. You need to import the react-redux library
  2. You need to mock the function
  3. You need to add the mockImplementation to provide a response value

Having all three pieces should make it work.

import { useSelector } from "react-redux";

jest.mock("react-redux", () => ({
  ...jest.requireActual("react-redux"),
  useSelector: jest.fn(),
}));

describe("MySearchComponent", () => {
  beforeEach(() => {
    useSelector.mockImplementation(callback => {
      return callback(mockAppState);
    });
  });
  test(() => {
    // Your test here
  });
});
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
anshumanburman profile image
anshumanburman

what is "mockAppState"? can you please explain me more?

Thread Thread
 
fredrikbergqvist profile image
Fredrik Bergqvist

mockAppState is the mocked redux state that your component needs to be able to run.
It should include data for all redux nodes that the component is using.

Take a component like this:

//the redux state looks like this;
// {
//   name: "Fredrik",
//   title: "Developer"
// }
import { useSelector } from "react-redux";
const MyComponent = () => {
  const reduxState = useSelector((state) => state)
  return (<h1>Hello {reduxState.name}</h1>)
}
Enter fullscreen mode Exit fullscreen mode

A mocked app state for the above component would look like this:

{
  name: "Mocked name",
 }
Enter fullscreen mode Exit fullscreen mode

So that you can run tests against a state that you have full control over.