Daniel de la Cruz Calvo
Software Engineer and professional mentor for developers.
var ReactTestUtils = require('react-addons-test-utils');
// Create a shallowRenderer instance
const shallowRenderer = ReactTestUtils.createRenderer()
// Create an instance of the component to be tested
const myComponent = React.createElement(MyComponent)
// Render the component with the shallow renderer
shallowRenderer.render(myComponent)
// Get the output of the render method
const result = shallowRenderer.getRenderOutput()
// Create assertions for that result
expect(result).to.be.eql('whatever')// <button ref="button">...</button>
var node** = this.refs.button;
ReactTestUtils.Simulate.click(node);*Simulate needs a DOM to work
** node must be a React Component instance and not a React Element
import React from 'react'
import { shallow } from 'enzyme'
import MyComponent from './MyComponent'
import Foo from './Foo'
describe('<MyComponent />', () => {
it('renders three <Foo /> components', () => {
const wrapper = shallow(<MyComponent />)
expect(wrapper.find(Foo)).to.have.length(3)
})
})// Finds by React component
expect(wrapper.find(MyReactComponent)).to.exist
// Finds by DOM element
expect(wrapper.find('h1').hasClass('centered')).to.equal(true)
// Finds by class name
expect(wrapper.find('.my-button').hasClass('disabled')).to.equal(true)it('simulates click events', () => {
const onButtonClick = sinon.spy();
const wrapper = shallow(
<Foo onButtonClick={onButtonClick} />
);
wrapper.find('button').simulate('click');
expect(onButtonClick).to.have.property('callCount', 1);
});By Daniel de la Cruz Calvo
Approaches and tooling for testing React.JS applications
Software Engineer and professional mentor for developers.