I want to mock a simple component library react-native-indicators
with Jest. As the Jest documentation states:
Mocking Node modules
If the module you are mocking is a Node module (e.g.: lodash), the mock should be placed in the mocks directory adjacent to node_modules (unless you configured roots to point to a folder other than the project root) and will be automatically mocked. There's no need to explicitly call jest.mock('module_name').
Ok, makes sense. I created my own super plain implementation in __mocks__/react-native-indicators.js
:
import React, { PureComponent } from 'react';class MockMaterialIndicator extends PureComponent { render() { return <></>; }};export { MockMaterialIndicator as MaterialIndicator};
I now expect Jest to 'magically' use this implementation, just as the documentation states.
However, when running my tests, Jest still can't seem to find MaterialIndicator
:
TypeError: Cannot read properties of undefined (reading 'MaterialIndicator') 42 | : 'rgba(0,0,0,0)', 43 | }}>> 44 | <MaterialIndicator color={Colors.primary} /> | ^ 45 | </Animated.View> 46 | ); 47 | } at Loader (src/components/Loader/Loader.tsx:44:10)
Here's my full Loader
component for reference:
import React, {useEffect, useState} from 'react';import {MaterialIndicator} from 'react-native-indicators';import {Animated, ViewStyle} from 'react-native';import Colors from '../../themes/Colors';import styles from './styles';interface ILoaderRequiredProps { modalVisible: boolean;}interface ILoaderOptionalProps { withDarkOverlay: boolean; overrideStyles: ViewStyle;}interface ILoaderProps extends ILoaderRequiredProps, ILoaderOptionalProps {}// by default use the dark overlayconst defaultProps: ILoaderOptionalProps = { withDarkOverlay: true, overrideStyles: {}};function Loader(props: ILoaderProps) { const {modalVisible, withDarkOverlay, overrideStyles} = props; const [isLoading, setIsLoading] = useState(false); useEffect(() => { if (modalVisible !== isLoading) { setIsLoading(modalVisible); } }, [modalVisible]); if (isLoading) { return (<Animated.View style={{ ...styles.wrapper, ...overrideStyles, backgroundColor: withDarkOverlay ? 'rgba(0,0,0,0.5)' : 'rgba(0,0,0,0)', }}><MaterialIndicator color={Colors.primary} /></Animated.View> ); } return <></>;}Loader.defaultProps = defaultProps;export default Loader;
What am I doing wrong here? Why can't Jest find my mock React component?