Basics
Mount a react component in a test
import { mount } from 'enzyme'
describe('MyReactComponent', () => {
const $ = mount(
<MyReactComponent />
)
...
})
Now different expectations and finds can be used to test,
A React Class
expect($.find('MyReactClass').exists()).toBe(false)
An html element
expect($.find('button').exists()).toBe(false)
An html id
expect($.find('#my-id').exists()).toBe(false)
A style
expect($.find('.some-style').exists()).toBe(false)
Html properties
expect($.find('[aria-label="Save"]').exists()).toBe(false)
expect($.find('[title="Save"]').exists()).toBe(false)
Combination - Html element & Property
expect($.find('button[title="Save"]').exists()).toBe(false)
HTML / Text / Contains
Text content. Find the first of many 'myClass' css classes and check the text of the elementexpect($.find('.myclass').text()).toContain("My Value")
expect($.find('.myclass').text()).not.toContain("My Value")
expect($.find('.myclass').text()).toBe("The exact text")
As above but getting the whole html of the element rather than just the text
expect($.find('.myclass').at(0).html()).toBe("<div>something</div>")
Focus
Focus a field with enzyme
const inputField = $.find('#myInput')
inputField.getDOMNode().focus()
expect(document.activeElement.id).toBe('the id expected')
Props
Find an element and get the html propertiesconst button = $.find('[aria-label="My Button"]')
expect(button.props().disabled).not.toBe(true)
Once an element has been found the react props can be used for expectations by also using props()
expect($.find('MyReactClass').props().options).toEqual([{option: 'option1'}, {option: 'option2'}])