'how can I test react native components that includes PNGs images with Jest
As I have tested my application which has navigation that has png images in node modules but tests are failing.
Source codes of App.js
import React from 'react';
import {SafeAreaView} from 'react-native';
import {styles} from './src/assets/styles';
import {AppStack} from './src/components/navs/stacks/AppStack';
const App = () => {
//TODO: Designing ui for spend and scheduled :progress
// doing list of data from utils/index.js :done
//fech those data to screen that needs them
return (
<SafeAreaView style={styles.app}>
<AppStack />
</SafeAreaView>
);
};
export default App;
App-test.js
import 'react-native';
import React from 'react';
import App from '../App';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
renderer.create(<App />);
});
Expected Result: Test should render my App entry point which is is App.js Actual Result
Janviers-MacBook-Pro:credex janvier$ npm test
> [email protected] test
> jest
FAIL __tests__/App-test.js
● Test suite failed to run
/Volumes/D/Coding/credex/node_modules/@react-navigation/elements/lib/commonjs/assets/back-icon.png:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){�PNG
SyntaxError: Invalid or unexpected token
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
at Object.<anonymous> (node_modules/@react-navigation/elements/lib/commonjs/index.tsx:20:3)
Solution 1:[1]
Reason for the error is Jest failing to interpret the binary code of .png file (or any image file) into .js.
The solution or rather the way around is to mock a default response whenever Jest encounters an image file.
Steps:
- Create a file named ImageMock.js (.tsx if you're using TypeScript) in a folder named
__mock__(or any name).
YourApp/__mock__/ImageMock.js
- Write
export default '';in ImageMock.js - Add
moduleNameMapperkey with the below value within thejestkey in package.json
"jest": {
"moduleNameMapper": {
"\\.(png|jpg|ico|jpeg|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mock__/ImageMock.js"
}
}
NB: Only the png in the moduleNameMapper key value is required for your particular error.
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 |
