Mohsen Zia
Mohsen Zia

Reputation: 444

React Native testing components with depends on another components

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?

Upvotes: 0

Views: 627

Answers (1)

Vasyl Nahuliak
Vasyl Nahuliak

Reputation: 2478

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(),
  });
});

Upvotes: 1

Related Questions