Skip to content

Instantly share code, notes, and snippets.

@Theartbug
Last active August 20, 2018 00:53
Show Gist options
  • Save Theartbug/4972cf437c89aaf314272e7ad7328c15 to your computer and use it in GitHub Desktop.
Save Theartbug/4972cf437c89aaf314272e7ad7328c15 to your computer and use it in GitHub Desktop.

Snapshot testing react components with jest

Resources:

Why Enzyme?

  • utilities work with shallow rendering, static rendering, or DOM
  • API to find elements, read props

Important Jest matchers for snapshot testing:

  • .toMatchStanpshot() will compare the snapshot to the rendered UI. A snapshot is created the first time the test file is run.
  • jest -u in the CLI will update a snapshot to the new changed UI.
  • .any() will allow generated content within the snapshot to be anything. Pass in types to check against like Number or Boolean or Date.
  • .simulate() is used to simulate events such as click or hover
  • .find() will take a CSS selector and locate an element in the rendered component
  • .toHaveLength() can be used creatively to find the number of children after an element is interacted with

Enzyme methods

  • mount()
    • Ideal for use cases where you have components that may interact with DOM API, or use React lifecycle methods in order to fully test the component
    • As it actually mounts the component in the DOM .unmount() should be called after each tests to stop tests affecting each other
    • Allows access to both props directly passed into the root component (including default props) and props passed into child components
  • shallow()
    • Renders only the single component, not including its children. This is useful to isolate the component for pure unit testing. It protects against changes or bugs in a child component altering the behaviour or output of the component under test
    • As of Enzyme 3 shallow components do have access to lifecycle methods by default
    • Cannot access props passed into the root component (therefore also not default props), but can those passed into child components, and can test the effect of props passed into the root component. This is as with shallow(), you're testing what MyComponent renders - not the element you passed into shallow
  • render()
    • renders static HTML, including children
    • does not have access to react lifecycle methods
    • less costly than mount but provides less functionality
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment