Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@oonsamyi
Forked from fokusferit/enzyme_render_diffs.md
Last active October 21, 2019 07:21
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save oonsamyi/2422357b4e68a4461dcd11b7724291eb to your computer and use it in GitHub Desktop.
Save oonsamyi/2422357b4e68a4461dcd11b7724291eb to your computer and use it in GitHub Desktop.
Difference between Shallow, Mount and render of Enzyme

Shallow

Real unit test (isolation, no children render)

Simple shallow

Calls:

  • constructor
  • static getDerivedStateFromProps
  • render
  • componentDidMount

Shallow + setProps

Calls:

  • shouldComponentUpdate
  • static getDerivedStateFromProps
  • render
  • componentDidUpdate

(shouldComponentUpdate must invoke after getDerivedStateFromProps, is it a bug? in mount mode the order is right)

Shallow + unmount

Calls:

  • componentWillUnmount

Mount

Full rendering including child components. Requires a DOM (jsdom, domino). More constly in execution time.

Simple mount

Calls:

  • constructor
  • static getDerivedStateFromProps
  • render
  • componentDidMount

Mount + setProps

Calls:

  • static getDerivedStateFromProps
  • shouldComponentUpdate
  • render
  • getSnapshotBeforeUpdate
  • componentDidUpdate

Mount + unmount

Calls:

  • componentWillUnmount

Render

Calls:

  • constructor
  • static getDerivedStateFromProps
  • render

missing any methods on wrapper (setProps, update, unmount, ...)

So my rule of thumbs is:

  • Always begin with shallow
  • If you want to test component with all lifecycle methods (e.g. getSnapshotBeforeUpdate) and in the right order and children behavior, use mount
  • If you want to test children rendering with less overhead than mount and you are not interested in lifecycle methods, and you do not need wrapper methods, use render

There seems to be a very tiny use case for render. I like it because it seems snappier than requiring jsdom but as @ljharb said, we cannot really test React internals with this.

I wonder if it would be possible to emulate lifecycle methods with the render method just like shallow ? I would really appreciate if you could give me the use cases you have for render internally or what use cases you have seen in the wild.

I'm also curious to know why shallow does not call componentDidUpdate.

Kudos goes to enzymejs/enzyme#465 (comment) this gist is basically a copy of the comment but I wanted to separate it from there as it includes a lot of general Enzyme information which is missing in the docs.

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