Debug an element: console.log(element.debug())
Test the html rendered: expect(element.html()).toEqual('<div>content</div>');
Find a component: element.find('ComponentName')
or element.find(ComponentName)
eg: expect(element.find('Component').length).toBe(1)
expect(element.find('Component')).toBePresent()
Test the component prop: expect(element.find('Component')).toHaveProp('message', 'there is an error')
Test component method:
const element = shallow(<Component />);
const instance = element.instance()
expect(instance.sayHello()).toEqual('hello')
Spies and simulations:
If you have to spy on a component method for event tests, you would have to call element.update()
after spying to bind the spy to the instance
enzymejs/enzyme#365
Currently, event simulation for the shallow renderer does not propagate as one would normally expect in a real environment. As a result, one must call .simulate() on the actual node that has the event handler set.
Simulate text field change:
element.find('input').simulate('change', {target: {value: 'some text'}});
Update the props of a rendered component to trigger componentWillReceiveProps:
component.setProps(newProps);
Testing jsx returned (not rendered) by methods:
import ReactDOMServer from 'react-dom/server';
const resultAsString = ReactDOMServer.renderToString(testMethod()); //returns <div>Hello</div>
const resultAsStaticMarkup = ReactDOMServer.renderToStaticMarkup(testMethod());
expect(resultAsString).toEqual('<div>Hello</div>');
expect(resultAsStaticMarkup).toEqual('Hello');
Test that the component jsx is null (does not render):
expect(component.type()).toBeNull()
Get the DOM node object from an enzyme wrapper:
component.getDOMNode().click()
When a child component of the component you are testing uses redux's
connect()
, you have to wrap your component selector withConnect()
.defaultElement.find('FinanceAmountField')
will no longer work when FinanceAmountField is "connected" instead use:defaultElement.find('Connect(FinanceAmountField)')