DEV Community

Discussion on: Mocking redux useSelector-hook

Collapse
 
sergey_dubovik_1db68b2f23 profile image
Sergey Dubovik • Edited

Frederik, thanks for the article - really helped me testing certain component in our app!
For those who are stumble upon it and need to test components with multiple useSelector's, do as article suggests, and add this:

//Mock your selectors
jest.mock('path/to/selectors', () => {
    const ActualHelpers = jest.requireActual('path/to/selectors');
    return {
        ...ActualHelpers,
        selectorNumberOne: jest.fn(),
        selectorNumberTwo: jest.fn(),
    };
});

//and then inside of your it()/test():
selectorNumberOne.mockReturnValue('value you need')
selectorNumberTwo.mockReturnValue('value for selector #2') // and so on
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sklinov profile image
Sergei

Thanks, Fredrick for the article and Sergey for that comment.
I have a slightly different setup: I've wrapped RTL render with my redux-dynamic-modules provider, so I think there's no need to mock react-redux or useSelector, and all I need to actually mock is the return value of my selector function.

I'm trying to implement it the way shown in your comment, but I'm getting an error that my selector is undefined.

Collapse
 
sergey_dubovik_1db68b2f23 profile image
Sergey Dubovik

Paste your code here

Thread Thread
 
sklinov profile image
Sergei • Edited
...
import { userListSelector } from "@/redux/user/user.selector";

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

jest.mock("@/redux/user/user.selector", () => {
  const actualUserSelectors = jest.requireActual("@/redux/user/user.selector");
  return {
    ...actualUserSelectors,
    userListSelector: jest.fn(),
  };
});

describe("Render Component", () => {
  beforeEach(() => {
    documentBody = render(
      <Component />,
      undefined,
      [reduxUser()] // this is dynamic module wrapper
    );
    (useSelector as jest.MockedFunction<typeof useSelector>).mockImplementation((selector: any) => {
      return selector();
    });

    (userListSelector as jest.MockedFunction<typeof userListSelector>).mockReturnValue({
      loading: false,
      users: createMockList<UserType>(3),
    });
  });

  afterEach(() => {
    cleanup();
  });

  test("Should render ProfileTable", () => {
    expect(documentBody.getByTestId(TestId.Component)).toBeInTheDocument();
  });
});

Enter fullscreen mode Exit fullscreen mode

And I get Cannot destructure property 'users' of 'react_redux_1.useSelector(...)' as it is undefined. error from component