@commercetools/enzyme-extensions
Why should you use this? Read:
Test a Render Prop!
NOTE This package used to provide a renderProp test helper, which is now part of enzyme itself as of v3.8.0 🎈.
We therefore dropped renderProp in v4.0.0 of this package. We recommend to use renderProp from enzyme itself instead.
Be aware that the API has changed while moving the function to enzyme.
wrapper.renderProp('foo', 10, 20);
wrapper.renderProp('foo')(10, 20);
We are happy that our little helper has made it into enzyme.
What assumptions is this built with?
- We like to shallow render and avoid mounting
- 🤺 Shallow rendering is fast and ensures that you only interact with the unit under test
- 🏙 Shallow rendering ensures that you do not snapshot past your test's concern
- 🏎 Shallow rendering has shown to be more performant for us than mounting
- We like declarative components and Render Props
- 🧠 We can compose components easily while following along their interactions
- 🔪 We like stubbing to test individual pieces of logic
Installation
1. Add package
yarn add @commercetools/enzyme-extensions -D
2. Add a test setup file (test runner dependent)
For Jest you would set up a setupTestFrameworkScriptFile.
Create that file and add it to the jest configuration.
3. Extend Enzyme with this package's helpers
In that testFrameworkScriptFile file, import the extensions and add them to Enzyme
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-xx';
import configure from '@commercetools/enzyme-extensions';
import ShallowWrapper from 'enzyme/ShallowWrapper';
Enzyme.configure({ adapter: new Adapter() });
configure(ShallowWrapper);
Usage
Once set up, you can use the extension in your test files like this:
import React from 'react';
import { shallow } from 'enzyme';
describe('when rendering `<App>`', () => {
const App = () => (
<div id="app">
<Mouse
render={(x, y) => (
<div>
Cursor is at {x} {y}
</div>
)}
/>
</div>
);
const wrapper = shallow(<App />)
.find(Mouse)
.drill(props => props.render(10, 20));
it('should render the mouse position', () => {
expect(wrapper.equals(<div>Cursor is at 10 20</div>)).toBe(true);
});
});
Enzyme's renderProp is built as an easy to use test helper for the most common cases.
In case you need more control, you can use drill instead. drill offers more flexibility as:
- the prop-to-call can be derived from the other props
- the returned element can be set dynamically
See the drill documentation for more.
Documentation