Reputation: 3448
Below is a a little test file that I made for a React project that is using both Jest and Enzyme for testing. In this test, I'm simply trying to find an element in the component and see that it exists (as a truthy conditional). The whole point of this test wasn't just to see if the element existed, but I figured I'd start here. I'm very new to testing, so this syntax/implementation may be bonkers:
import React from 'react';
import ReactDOM from 'react-dom';
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import HamburgerIcon from './HamburgerIcon';
Enzyme.configure({ adapter: new Adapter() });
test('my first test -- will add better text here later', () => {
const div = document.createElement('div');
ReactDOM.render(<HamburgerIcon />, div);
expect(div.find('.closed').exists()).toBeTruthy();
ReactDOM.unmountComponentAtNode(div);
});
Running this results in this error:
TypeError: div.find is not a function
I originally built this test after seeing this Stack Overflow answer.
I'm not sure how to troubleshoot this, but I'm guessing that maybe I haven't properly "mounted" the component in this test? In the same Stack Overflow thread from the previous link, this answer shows how you would mount a component, but another comment on that answer says that another package needs to be installed in order to do that.
I sort of figured that using the div
variable as the container to be searched with find
would work, but am I wrong in thinking that?
Upvotes: 0
Views: 4025
Reputation: 5473
Here's the sample code for you, may not be 100% what you need but should get you started. I also included console.log
so that you know what gets rendered.
To explain a bit on what happens, is in your test case you are calling shallow
method and passing your React component to it to render. Test cases are run in virtual browser/renderer not the real browser (unless you configure it that way).
import React from 'react';
import ReactDOM from 'react-dom';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import HamburgerIcon from './HamburgerIcon';
Enzyme.configure({ adapter: new Adapter() });
test('my first test -- will add better text here later', () => {
const wrapper = shallow(<HamburgerIcon />);
console.log(wrapper);
expect(wrapper.find('.closed').exists()).toBeTruthy();
});
Upvotes: 1