I am using jest with react-native to run unit test cases. And whenever it encounters Image
it throws the following warning
Warning: Failed prop type: Invalid prop `source` supplied to `Image`, expected one of type [number]. at Component (~/.../node_modules/react-native/jest/mockComponent.js:28:18) at SummaryTile (~/.../src/components/home/SomeComponent.tsx:18:3) 23 | > 24 | {backgroundImg || ( > 25 | <Image | ^ 26 | source={require('images/cloud.png')} 27 | />
I tried to replace the code to
<Image src={{uri: require('images/cloud.png')}} />
as suggested in https://stackoverflow.com/a/36460928/3855179 but it started throwing the following warning and the application breaks
Warning: Failed prop type: Invalid prop `source` supplied to `Image`, expected one of type [string, number]. at Image (http://expo_url:19000/node_modules/expo/AppEntry.bundle?platform=android&dev=true&hot=false&strict=false&minify=false:76209:43)
Jest Version: 26.6.3 React Native version: 0.64.3 Node Version: 16.14.2
Any idea how this can be handled?
Advertisement
Answer
It would be helpful to see your file structure along with the jest configuration file.
But my best guess is – jest isn’t able to find the file in the designated location.
Few things that can be tried:
(1) try changing file location to be a bit more explicit like so:
eg – if image in same directory — source={require('./images/cloud.png')}
eg – if one directory up — source={require('../images/cloud.png')}
(2) try mocking out the image in test file like so:
jest.mock("images/cloud.png")
(3) Specify a location in jest configuration file (or in package.json file if you have a jest key there) for all image types, this way jest will use that as the image source whenever it encounters an image:
eg –
moduleNameMapper: { "\.(jpg|jpeg|png|svg)$": "<rootDir>/images/dummy-image.js", }
More doco on moduleNameWrapper here – https://jestjs.io/docs/configuration#modulenamemapper-objectstring-string–arraystring