__mock__/react-redux.js
파일에 export 한다export const useSelector = jest.fn();
export const useDispatch = jest.fn();
test할 코드에서 jest.mock('react-redux')
사용
useSelector mock 함수를 설정
export const CATEGORIES = [
{
id: 1,
name: '한식',
},
{
id: 2,
name: '양식',
},
{
id: 3,
name: '일식',
},
{
id: 4,
name: '중식',
},
];
useSelector.mockImplementation((selector) => selector({
categories: CATEGORIES,
}));
// categoriesContainer.test.jsx
describe('CategoriesContainer', () => {
useSelector.mockImplementation((selector) => selector({
categories: CATEGORIES,
}));
it('render', () => {
const { container } = render(<CategoriesContainer categories={CATEGORIES} />);
expect(container).toHaveTextContent('한식');
});
});
// categoriesContainer.jsx
export default function CategoriesContainer() {
const { categories } = useSelector((state) => ({
categories: state.categories,
}));
return <Categories categories={categories} />;
}
npm test 결과
참고 : https://dev.to/fredrikbergqvist/mocking-redux-useselector-hook-2ale