Skip to content

Instantly share code, notes, and snippets.

@jahe
Last active June 3, 2022 01:18
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save jahe/9bf2cb1f849b7ed96c6ce20ede7f66a2 to your computer and use it in GitHub Desktop.
Save jahe/9bf2cb1f849b7ed96c6ce20ede7f66a2 to your computer and use it in GitHub Desktop.
Enzyme Cheatsheet
// Show rendered HTML
const wrapper = shallow(<App />)
console.log(wrapper.debug())
// Disable lifecycle methods of react within tests
const wrapper = mount(<App />, { disableLifecycleMethods: true })
// Assert number of occurrences
expect(wrapper.find('p').length).toBe(1)
// Assert existence of a node
expect(wrapper.find('p').exists()).toBe(true)
// Assert count of children
expect(wrapper.find('ul').children().length).toBe(3)
// Assert text within a DOM node
expect(wrapper.find('h1').text()).toBe('Welcome to React')
// 5 valid types of selectors
// Element - searches for HTML tags like 'p'
// Class - searches for CSS classes on DOM nodes
// ID - searches for IDs set on DOM nodes
// Attribute - searches for an attribute set on DOM nodes or on React components (passed via props)
// A combination - searches for a combination of them
// Find nodes by React props
wrapper.find({alt: 'logo'})
// Unit tests have holes that are not being tested and the structure (<h1> comes before the <p>) is hard and verbose to test
// Therefore we can use Snapshot tests to match the structure of a component against a former snapshot
// The first time we run the test it passes automatically and a snapshot file is generated (in a __snapshots__ directory with the filename App.test.js.snap)
const tree = shallow(<App />)
expect(tree).toMatchSnapshot()
// The snapshot files are unreadable
// To change that we can install enzyme-to-json as a dev dependency
// The output looks like the HTML rendered version of the component which is much more readable
import toJson from 'enzyme-to-json'
const tree = shallow(<App />)
expect(toJson(tree)).toMatchSnapshot()
// Assert on specific props
// With instance() we get the React element
const wrapper = shallow(<Link address="www.google.com" />)
expect(wrapper.instance().props.address).toBe('www.google.com')
// Assert attributes of a HTML tag
// With props() we get the attributes of the DOM node of that React component
const wrapper = shallow(<Link address="www.google.com" />)
expect(wrapper.props().href).toBe('www.google.com')
// Set props of a tested component (useful for testing props changing over time)
// setProps(nextProps) receives an object of props which are being merged with the current ones - it triggers a re-render of the component
// get(index) receives a React element
const wrapper = shallow(<Link hide={false} />)
expect(wrapper.find('a').length).toBe(1)
wrapper.setProps({ hide: true })
expect(wrapper.get(0)).toBeNull()
// Use real DOM rendering with mount() to test interactions with the DOM API or the React lifecycle methods
// Components rendered with mount() have to be unmounted to not influence the next tests
const wrapper = mount(<App />)
expect(wrapper.find('h1').text()).toBe('Welcome to React')
wrapper.unmount()
// Simulate a click event
const wrapper = shallow(<App />)
const button = wrapper.find('button')
button.simulate('click')
// Simulate text input field changes
// change() takes an additional event object that can be mocked out for our method
const wrapper = shallow(<App />)
const input = wrapper.find('input')
input.simulate('change', { currentTarget: { value: 'Hello' }})
// Change state of the Component under test
// setState() triggers a re-render of the component
const wrapper = shallow(<App />)
wrapper.setState({ mainColor: 'red' })
// Spy on a specific method of a class
// In this case we would like to track the use of the componentDidMount() lifecycle method and check whether it is being called
jest.spyOn(App.prototype, 'componentDidMount')
const wrapper = shallow(<App />)
expect(App.prototype.componentDidMount.mock.calls.length).toBe(1)
// Test instance methods of a React component
const wrapper = shallow(<App />)
const trueReturn = wrapper.instance().handleStrings('Hello World')
expect(trueReturn).toBe(true)
// Mock out a specific function imported from a module
const wrapper = shallow(<App />)
jest.spyOn(api, 'addUser').mockImplementation(() => Promise.resolve({ data: 'New user added' }))
wrapper.find('[test-dataid="addUserForm"]').simulate('submit', { preventDefault: () => {}})
expect(api.addUser).toHaveBeenCalledWith('Peter', 'peter@hansen.de', '234234')
@dineshkp-dev
Copy link

Thank you for the cheat sheet

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment