Closed anantoghosh closed 6 years ago
@anantoghosh. Thank you for the PR. It was very much needed. I have a doubt like where should this code be added(as in which file) for testing?? I haven't worked with react-enzyme. Can you help me here in understanding it??
Every component can have tests in componentname.test.js file, which will be executed with npm run test
Like App.test.js already present in the repo.
Additionally a __tests__
folder can be created for tests using multiple components.
Enzyme at top level provides 3 rendering functions for react components. shallow, mount and render. shallow() - most commonly used - will render the component in isolation without rendering its children components. mount() will render the complete component with its children components. render() will render react components to static HTML
Once rendered, enzyme provides a list of methods to query or modify the components.
const wrapper = shallow(<MyComponent />);
expect(wrapper.find('.foo')).to.have.length(1);
wrapper.setProps({ name: 'bar' });
expect(wrapper.contains(<div data-foo="foo" data-bar="bar">Hello</div>)).to.equal(true);
Full list here: http://airbnb.io/enzyme/docs/api/shallow.html
describe
, test
, it
, expect
and methods chaining to expect are provided by jest. These are similar to any other testing frameworks you may have seen or used.
With jest we could use snapshot testing
expect(wrapper).toMatchSnapshot();
Which is a json representation of the rendered react component at the time of execution.
When ever toMatchSnapshot()
is executed. It will look for a previously created snapshot stored in __snapshots__
folder. If not found, it will create a new snapshot. If found, it will compare the snapshots and report any differences as errors. The developer then has to verify if the change was intended or not. Jest provides an interactive cli for updating snapshots.
These snapshots have to be committed to the repo as well.
jest-enzyme
package provides us with additional assertions for expect
which simplify testing.
Eg:
expect(wrapper).toHaveState({ foo: 'bar' });
full list https://github.com/FormidableLabs/enzyme-matchers#assertions
Testing is not enforced, it will not interfere with development if anyone is unsure on how to use it.
LGTM :+1:
This PR adds enzyme and helper libraries for easy react component testing.
packages added: enzyme enzyme-adapter-react-16 enzyme-to-json (allow enzyme to create snapshots) jest-enzyme (helper matchers)
Testing simple components is now as easy as: