Reputation: 1110
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'));
Upvotes: 1
Views: 2187
Reputation: 884
There's a couple of simple approaches here for you to consider:
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.)
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);
Upvotes: 1