Enzyme: Enzyme does not call useEffect with update() on wrapper created via mount

Created on 4 Oct 2019  路  5Comments  路  Source: enzymejs/enzyme

Current behavior

useEffect is not called on wrapper.update() (wrapper created via mount).

Expected behavior

I would expect useEffect to be called in this situation. As a workaround, I am using setProps() instead of update()

Your environment

OS X 10.14.5

API

  • [ ] shallow
  • [x] mount
  • [ ] render

Version

| library | version
| ------------------- | -------
| enzyme | 3.10.0
| react | 16.9.0
| react-dom | 16.9.0
| react-test-renderer | 16.9.0
| adapter (below) | 1.14.0

Adapter

  • [x] enzyme-adapter-react-16
  • [ ] enzyme-adapter-react-16.3
  • [ ] enzyme-adapter-react-16.2
  • [ ] enzyme-adapter-react-16.1
  • [ ] enzyme-adapter-react-15
  • [ ] enzyme-adapter-react-15.4
  • [ ] enzyme-adapter-react-14
  • [ ] enzyme-adapter-react-13
  • [ ] enzyme-adapter-react-helper
  • [ ] others ( )

Example Code

App.js

import React from 'react';

export default function App() {
  React.useEffect( () => {} );
  return <div />;
}

App.test.js

import React from 'react';
import Enzyme, { mount } from 'enzyme';
import App from './App';
import EnzymeAdapter from 'enzyme-adapter-react-16';

Enzyme.configure({ adapter: new EnzymeAdapter() });

test("useEffect is called on update", () => {
  const mockUseEffect = jest.fn();
  React.useEffect = mockUseEffect;

  const wrapper = mount(<App />);

  mockUseEffect.mockClear();
  wrapper.update();

  expect(mockUseEffect).toHaveBeenCalled();
});

If I replace wrapper.update() with wrapper.setProps(), the test passes.

Most helpful comment

Ah - wrapper.update() does not force a rerender, so you'd need something like setProps to force that. You could also use, say, useState inside App and setState inside the component, forcing a rerender, and I'd expect it to run then as well.

All 5 comments

Ah - wrapper.update() does not force a rerender, so you'd need something like setProps to force that. You could also use, say, useState inside App and setState inside the component, forcing a rerender, and I'd expect it to run then as well.

Should the docs be update to reflect that? The docs say that calling update "forces a re-render".

@michelmattos already done in #2194.

I've created a package that solves the issue - https://www.npmjs.com/package/jest-react-hooks-shallow

@mikeborozdin thanks for package it really helps.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ahuth picture ahuth  路  3Comments

blainekasten picture blainekasten  路  3Comments

rexonms picture rexonms  路  3Comments

ivanbtrujillo picture ivanbtrujillo  路  3Comments

nelsonchen90 picture nelsonchen90  路  3Comments