Sun Jan 29 2023

[SOLVED] TypeError: (0 , _reactRedux.useSelector) is not a function

An explanation as to why this error occurs and how to overcome this

Recently I was upgrading some old components in a react app.  One of those components was wrapped with the connect() function which connects a React component to a Redux store. 

One of the expectations of the work that I was doing on this component was that I would remove the connect() and obtain the data needed for that component using the new useSelector() hook. So I did just that and after some manual checks, ran my pre-commit tests and was met with the error message that one of my tests was failing due to TypeError: (0 , _reactRedux.useSelector) is not a function. The failing test looked something like this.

1jest.mock("react-redux", () => ({
2 connect: () => (Component) => Component,
3}));
4describe("App component tests", () => {
5 test("should match snapshot", () => {
6 const { container } = render(<Component />);
7 expect(container).toMatchSnapshot();
8 });
9});

As you can see the test is mocking the connect from React Redux, which is no longer used in our component! The fix was to mock the useSelector() hook and remove the connect(). 

1jest.mock("react-redux", () => ({
2 useSelector: jest.fn(),
3}));
4describe("App component tests", () => {
5 test("should match snapshot", () => {
6 const { container } = render(<Component />);
7 expect(container).toMatchSnapshot();
8 });
9});

And the tests passed as the useSelector() is now mocked!

Keep in mind that if you are testing a functionality in your component that requires some data to be fetched from the useSelector, then you would have to mock this. I will write another article on this soon!

Bonus - if the above solution doesn't work, make sure to take a careful look at your imports in the tests. You might be importing useSelector from React instead of Redux!

If you found this article useful, let me know. Have comments or ideas on more content you would like to see from me? Also, let me know (in the comments below!).

Comments