npx create-react-app . npm i -D enzyme jest-enzyme npm i -D @wojtekmaj/enzyme-adapter-react-17
Jest is installed as a part of create-react-app
enzyme-adapter-react-17 not yet available
shallow()
is used to render a component for tests
.find()
tests that required DOM element was rendered. data-test
attribute is used for this purpose.
.text()
Enzyme's method to extract the text of an element. span
can be used here
to interact with rendered elements (i.e. click button)
setup()
and findByTestAttr
re-usable functionsconst App = () => { const [count, setCount] = useState(0); return ( <div data-test="component-app"> <h1 data-test="counter-display">The counter is currently <span data-test='count'>{count}</span></h1> <button data-test="increment-button" onClick={() => setCount(count + 1) }>Increment counter</button> </div> ); }
import Enzyme, { shallow } from 'enzyme'; import EnzymeAdapter from '@wojtekmaj/enzyme-adapter-react-17'; import App from './App'; Enzyme.configure({ adapter: new EnzymeAdapter() }); /** * Factory function to create a ShallowWrapper for the App component. * @function setup * @returns {ShallowWrapper} */ const setup = () => shallow(); // shallow rendering of component const findByTestAttr = (wrapper, val) => { return wrapper.find(`[data-test="${val}"]`); }
test('renders without error', () => { const wrapper = setup(); const appComponent = findByTestAttr(wrapper, 'component-app'); expect(appComponent.length).toBe(1); });
test('renders button', () => { const wrapper = setup(); const button = findByTestAttr(wrapper,'increment-button'); expect(button.length).toBe(1); });
test('renders counter display', () => { const wrapper = setup(); const counterDisplay = findByTestAttr(wrapper,'counter-display'); expect(counterDisplay.length).toBe(1); });
test('counter starts at 0', () => { const wrapper = setup(); const count = findByTestAttr(wrapper,'count').text(); // text - returns a string expect(count).toBe("0"); });
test('clicking on button increments counter display', () => { const wrapper = setup(); // Find the button const button = findByTestAttr(wrapper,'increment-button'); // Click the button button.simulate('click'); // Simulate a click // Find the display, and test that the number const count = findByTestAttr(wrapper,'count').text(); // text - returns a string expect(count).toBe("1"); });