'Jest: Failed prop type: Invalid prop `source` supplied to `Image`, expected one of type [number]
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?
Solution 1:[1]
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
Solution 2:[2]
In my case, I was trying to use an image, that has an space in its name, like <rootDir>/stupidly_named images.png. It's seems, React Native is happy with these naming, but not Jest. Filling in the space (<rootDir>/stupidly_named_images.png) fixed the error. And I am not using any moduleNameWrapper:
"react-native": "0.68.2"
"jest": "^28.1.0"
"@testing-library/react-native": "^9.1.0"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nishkaush |
| Solution 2 | Kasra |
