I'm using Jest
and react-test-renderer
for test my components. When I test pure component with import only from react-native
modules, everything is ok.
for example when I test below component:
import React from 'react';
import {Text, View} from 'react-native';
export default class Splash extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<View testID={'splash-test-1'}>
<Text>This is Splash Screen</Text>
</View>
);
}
}
with below code, test will passed and no problem:
it('Splash Screen', () => {
const screen= renderer.create(<Splash/>).root;
expect(screen.findByProps({testID: 'splash-test-1'}).children.length).toBe(1);
})
But when I add any modules, like RBFetchblob (e.g import RNFetchBlob from "rn-fetch-blob";
) on top of my code, I get an error. for example in importing RNFetchblob, get follow error:
ā Test suite failed to run
D:\Projects\MyProject\node_modules\rn-fetch-blob\index.js:5
import {
^^^^^^
SyntaxError: Cannot use import statement outside a module
......
My question is how can I test react native components in a real project with many dependencies?
Need to use mocks https://jestjs.io/docs/manual-mocks#mocking-node-modules
For your example, in root project need create __mocks__
folder and put file rn-fetch-blob
with code:
jest.mock('rn-fetch-blob', () => {
return () => ({
fs: jest.fn(),
config: jest.fn(),
DocumentDir: jest.fn(),
});
});