Search code examples
reactjsjestjsreact-dom

Unit Testing the root component of the React Web Application


How to test the root component which is rendered through react-dom render function?

I am working on this react component.

 export default class EWAWeb extends React.Component {
    render() {
        return (
            <Provider store={store} >
                <Router>
                    <Switch>
                        <Route exact path="/" component={SplashScreen} />
                        <Route path="/start" component={SplashScreen} />
                        <Route path="/dashboard" component={Dashboard} />
                    </Switch>
                </Router>
            </Provider>
        );
    }
}

render(<EWAWeb />, document.getElementById('app'));

Inside JEST

describe('To test the Login Component functionality.', () => {
    configure({ adapter: new Adapter() });
    let compEWAWebParent = null;

    it(`should mount and check.`, () => {
            compEWAWebParent = mount(<EWAWeb />);
            const isReduxProvider = compEWAWebParent.find(Provider);
            expect(isReduxProvider).toHaveLength(1);
        });
});

I am writing this simple test to check. If I remove the below line, test is working well,

render(<EWAWeb />, document.getElementById('app'));

otherwise throwing error:

Invariant Violation: Target container is not a DOM element.

I don't want to segregate the files and also don't want to use document .body.

Thank you.

The issue is resolved and I have achieved 100% code coverage.

Thank you.

Solution

export default class EWAWeb extends React.Component {
    render() {
        return (
            <Provider store={store} >
                <Router>
                    <Switch>
                        <Route exact path="/" component={SplashScreen} />
                        <Route path="/start" component={SplashScreen} />
                        <Route path="/dashboard" component={Dashboard} />
                    </Switch>
                </Router>
            </Provider>
        );
    }
}

const containerDiv = document.getElementById('app');
render(<EWAWeb />, containerDiv || document.createElement('DIV'));

Solution

  • There's a couple of simple approaches here for you to consider:

    1. Put the Router component and its children into their own component, which you can unit test easily and thoroughly, while not unit testing the resulting hollowed-out EWAWeb component at all. (Automated acceptance tests would cover checking the basic React wiring-up that the EWAWeb component represents.)

    2. Only call render when document.getElementById returns a valid object, so that you don't get an error when unit testing:

    const appElement = document.getElementById('app'); appElement && render(<EWAWeb />, appElement);