Reputation: 1812
I am trying to use Jest in my project like below to test my App class:
it('renders correctly', () => {
const tree = renderer
.create(<Router><App /></Router>)
.toJSON();
expect(tree).toMatchSnapshot();
});
But I get errors from a vendor module and error is like this:
TypeError: Cannot read property 'addEventListener' of null
at node_modules/hammerjs/hammer.js:222:16
I have no idea how to fix it
Upvotes: 0
Views: 626
Reputation: 1554
Why it doesn't work?
renderer.create
renders React components to pure JavaScript objects, without depending on the DOM or a native mobile environment.
Reference: https://reactjs.org/docs/test-renderer.html#testrenderercreate
Is you see hammerjs/hammer
's implementation you will find that addEventListener
is being called on a target DOM Element after finding it in the rendered component. When a DOM environment is not present the target DOM element turns out to be null
and hence the error.
How to fix it?
If you'd like to assert, and manipulate your rendered components you can use Enzyme or React's TestUtils.
Reference: https://facebook.github.io/jest/docs/en/tutorial-react.html#dom-testing
You can use Enzyme's mount
for Full DOM Rendering when you have elements that interact with the DOM.
http://airbnb.io/enzyme/docs/api/mount.html
So this should work:
it('renders correctly', () => {
const tree = mount(<Router><App /></Router>);
expect(tree).toMatchSnapshot();
});
Upvotes: 3