I've got a simple component that uses the useSelector and useDispatch hooks to dispatch and get the current state from my redux store and map over them to return a child component.
I'm new to testing with hooks and after following some articles, I mocked the two redux hooks with jest mock to see if they are called when mounted, however, when running the test my state array is returned as undefined so the test fails. Does anyone know why this is happening?
COMPONENT.tsx
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getData } from '../actions/index';
import { AppState } from '../store/store';
import GridItem from '../component/GridItem';
function GridContainer () {
const dispatch = useDispatch();
const books = useSelector((state: AppState) => state);
useEffect(() => {
dispatch(getData());
}, [dispatch]);
const bookList = (list: AppState) => {
return list.map((book) => (
<GridItem key={book.id} data={ book } />
))
};
return (
<div className="book-container">
{ bookList(books) }
</div>
)
}
export default GridContainer;
COMPONENT.test.tsx
import React from 'react';
import { shallow, mount } from 'enzyme';
import GridContainer from './GridContainer';
const mockDispatch = jest.fn();
jest.mock("react-redux", () => ({
useSelector: jest.fn(fn => fn()),
useDispatch: () => mockDispatch
}));
it('renders container', () => {
const wrapper = shallow(<GridContainer />);
const component = wrapper.find('.book-container');
expect(component.length).toBe(1);
});
describe('react hooks', () => {
afterEach(() => {
jest.clearAllMocks();
});
it('runs dispatch on mount', () => {
const wrapper = mount(<GridContainer />);
expect(mockDispatch).toHaveBeenCalledTimes(1);
});
});
ERROR msg
TypeError: Cannot read property 'map' of undefined
25 | //function to print list of books component
26 | const bookList = (list: AppState) => {
> 27 | return list.map((book) => (
| ^
28 | <GridItem key={book.id} data={ book } />
29 | ))
30 | };