1

Its been 7 days, I've tried reading every blog around this and nothing seems to be working.

Issue

I need to mock ```useSelector``` and ```useDispatch``` for my React FC.

Component:

/* renders the list of the apis */
const ApiSection = ({ categories }) => {
  const [page, setPage] = useState(0);
  const [query, setQuery] = useState('');
  const [search, setSearch] = useState(false);

  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(fetchAllApis({ page, category: categories, query }));
  }, [page, categories, dispatch, search]);

  // all these three are showing as undefined when consoled for UNIT TESTS !!!!!!!
  const { apiList, error, loading } = useSelector((state) => {
    return state.marketplaceApiState;
  });
  const renderApiCards = () => {
    let apis = Object.values(apiList);
    return apis.map((each) => (
      <ApiCard key={each.apiId} info={each} data-test="ApiCard" />
    ));
  };
  return (
    <div className="ApiSection" data-test="ApiSection">
      <div className="ApiSection__search">
      <div className="ApiSection__cards">{renderApiCards()}</div>
      <button onClick={() => setPage(page - 1)}>Previous</button>
      <button onClick={() => setPage(page + 1)}>Next</button>
    </div>
  );
};
export default ApiSection;

Test:

const initialState = {
  marketplaceApiState: {
    apiList: {
      a123: { name: 'name', description: 'desc', categories: 'cat', apiId: 'a123'},
    },
  },
};
const mockDispatch = jest.fn();
jest.mock('react-redux', () => ({
  ...jest.requireActual('react-redux'),
  useSelector: () => initialState,
  useDispatch: () => mockDispatch,
}));

const setup = () => {
  const store = createTestStore(initialState);
  // I have also tried mount with Provider
  return shallow(<ApiListSection categories={['a']} store={store} />);
};

describe('ApiListSection Component', () => {
  afterEach(() => {
    jest.clearAllMocks();
  });

  test('Calls action on mount', () => {
    setup();
    expect(useSelector).toHaveBeenCalled();
    expect(mockDispatch).toHaveBeenCalled();
  });
});

Error:

This is the error that I am getting:

let apis = Object.values(apiList);

I would really appreciate it, stuck for so many days

Karan Kumar
  • 2,678
  • 5
  • 29
  • 65
  • Does this answer your question? [How can I test a custom hook that is using the Redux hooks useDispatch and useSelector?](https://stackoverflow.com/questions/59442450/how-can-i-test-a-custom-hook-that-is-using-the-redux-hooks-usedispatch-and-usese) – Liam May 19 '23 at 09:35

1 Answers1

0

You ideally should not mock hooks but rather you should mock the store.

You should mock your store with something like this

And As far as I know enzyme does not have support for hooks you need to use @testing-library/react for good testing of your componenets that are using hooks

import { applyMiddleware, combineReducers, compose, createStore } from 'redux';
import thunk from 'redux-thunk';
import { homeReducer } from "../ducks/home";
import { jobReducer } from '../ducks/job';
import { toastReducer } from '../ducks/toast';

const composeEnhancers = compose;

const rootReducer = combineReducers({
    home: homeReducer,
    toast: toastReducer,
    job: jobReducer,
});

const enhancer = composeEnhancers(applyMiddleware(thunk));
export function createTestStore() {
    return createStore(rootReducer, enhancer);
}

You can refer to my POC repo here

I have used some well known tools there. All are listed in the readme.md of the repo.

nikhil mehta
  • 972
  • 15
  • 30