enzyme icon indicating copy to clipboard operation
enzyme copied to clipboard

ReactWrapper.update() is not forcing a re-render

Open nicholasrice opened this issue 5 years ago • 32 comments

Current behavior

min-repro here: https://github.com/nicholasrice/enzyme-react-wrapper-update-repro

Using mount to mount a component, calling the update method of the returned ReactWrapper instance does not seem to be forcing a re-render. With slight changes, I implemented the example from https://airbnb.io/enzyme/docs/api/ReactWrapper/update.html and am expierencing a test failure.

On a slight aside, I think the assertions being made in the above documentation should be 1 for the first call and 2 for the second call, instead of 0 for the first call and 1 for the second.

const React = require('react');
const Enzyme = require('enzyme');
const Adapter = require('enzyme-adapter-react-16');

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

test("ReactWrapper.update should re-render a react component", () => {
    const spy = jest.fn();

    class ImpureRender extends React.Component {
        constructor(props) {
            super(props);

            this.count = 0;
        }

        render() {
            this.count += 1;
            spy(this.count);

            return React.createElement("div", {}, this.count);

        }

    }

    const wrapper = Enzyme.mount(React.createElement(ImpureRender));

    expect(spy).toHaveBeenCalledTimes(1)

    // Update the component - should force re-render per https://github.com/airbnb/enzyme/blob/master/docs/api/ReactWrapper/update.md
    wrapper.update();

    expect(spy).toHaveBeenCalledTimes(2)
});

Expected behavior

I would expect that calling the update method of a ReactWrapper would call the render method of the mounted component.

Your environment

API

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

Version

library version
enzyme 3.9.0
react 16.8.4
react-dom 16.8.4
react-test-renderer 16.8.4
adapter (below) 1.10.0

Adapter

  • [x] enzyme-adapter-react-16

nicholasrice avatar Mar 09 '19 18:03 nicholasrice

Since this relies on an impure render (which is obviously a very bad idea in React), can you elaborate on the actual use case where this is popping up? If props and state and context haven't changed, a rerender shouldn't need to call render, even via enzyme's update.

ljharb avatar Mar 09 '19 21:03 ljharb

Yea the min-repro isn't a real use-case (but it is pulled from Enzyme documentation). I'm trying to write a test to validate that a context provider is providing the same context object between render cycles, and only providing a new object when a certain prop or parent context is changed. This involves checking object references after multiple renders of a component.

The above component could easily be changed to have a "pure" render by removing this.count and the issue would still manifest. The documentation says: "Forces a re-render." Apologies if I'm not understanding something here, but by that claim I would expect the render method of a React.Component that does not implement shouldComponentUpdate to get executed.

nicholasrice avatar Mar 10 '19 03:03 nicholasrice

Hmm, that does make sense. It does stand to reason that a call to update forces a rerender.

ljharb avatar Mar 10 '19 06:03 ljharb

Hi, I've also just run into the same issue. I definitely understand that impure renders are a bad idea, but in my case I'm testing something that involves mocking out a render prop component that relies on external state. The real version of the component updates its own state and re-renders, but in the mock it's easier to just craft calls to the children passed in. But that means only changing the mock's implementation of render, which means I need update to force a re-render.

Since you tagged as help wanted, is this a good place to start looking?

msakrejda avatar Mar 13 '19 22:03 msakrejda

@uhoh-itsmaciek yes, but be aware many other methods call into this.update(), and we may not want those to force a rerender.

ljharb avatar Mar 15 '19 20:03 ljharb

Interesting. Why would they be calling it? The internal documentation is the same: the method forces a re-render.

msakrejda avatar Mar 15 '19 20:03 msakrejda

They call it when state and/or props change, usually.

I'm just saying we'll have to be careful about it, and that it might be better to refactor so that the current behavior is preserved for all internal update attempts.

ljharb avatar Mar 15 '19 21:03 ljharb

Any updates on this?

ghbakhtiari avatar Jul 30 '19 11:07 ghbakhtiari

Nope, it's still open, has the "help wanted" label, and there's no associated PR.

ljharb avatar Jul 30 '19 20:07 ljharb

I'm having the same issue.

Doing wrapper.instance().forceUpdate() works for me but looking at the documentation I would expect wrapper.update() to do the same. I don't know how "safe" using forceUpdate is but for now it's fixed the problem for me.

hannaholl avatar Aug 07 '19 11:08 hannaholl

Having the same issue.

Having gone through this thread, the easiest solution is to update the docs, stating that it updates only if there were some changes to props/state. If update is an internal tool used by enzyme, there's no need to adapt it to invalid docs. Adapt docs to what update actually is.

ducin avatar Sep 05 '19 19:09 ducin

Event wrapped.instance().forceUpdate() doesn't re-render :(

let wrapped;
beforeEach(() => {
    wrapped = mount(
      <Provider store={store}>
        <Test />
      </Provider>
   );
});

it("disables submit button if it's already uploading a file", () => {
    const uploadButton = wrapped.find("#uploadButton");
    expect(uploadButton.prop("disabled")).toEqual(false);

    wrapped.instance().setState({ uploading: true }, () => {
        wrapped.instance().forceUpdate();
        
        expect(uploadButton.prop("disabled")).toEqual(false);
        // This is supposed to fail, but it passes
    });
});

Hiroki111 avatar Sep 07 '19 14:09 Hiroki111

What does wrapped.debug() look like, before the setState, and after the forceUpdate?

ljharb avatar Sep 07 '19 16:09 ljharb

I'm having the same issue.

Doing wrapper.instance().forceUpdate() works for me but looking at the documentation I would expect wrapper.update() to do the same. I don't know how "safe" using forceUpdate is but for now it's fixed the problem for me.

TypeError: wrapper.instance(...).forceUpdate is not a function ... I got this error

ghost avatar Sep 24 '19 11:09 ghost

Event wrapped.instance().forceUpdate() doesn't re-render :(

let wrapped;
beforeEach(() => {
    wrapped = mount(
      <Provider store={store}>
        <Test />
      </Provider>
   );
});

it("disables submit button if it's already uploading a file", () => {
    const uploadButton = wrapped.find("#uploadButton");
    expect(uploadButton.prop("disabled")).toEqual(false);

    wrapped.instance().setState({ uploading: true }, () => {
        wrapped.instance().forceUpdate();
        
        expect(uploadButton.prop("disabled")).toEqual(false);
        // This is supposed to fail, but it passes
    });
});
```This works

sameekshakumari avatar Oct 21 '19 05:10 sameekshakumari

Event wrapped.instance().forceUpdate() doesn't re-render :(

let wrapped;
beforeEach(() => {
    wrapped = mount(
      <Provider store={store}>
        <Test />
      </Provider>
   );
});

it("disables submit button if it's already uploading a file", () => {
    const uploadButton = wrapped.find("#uploadButton");
    expect(uploadButton.prop("disabled")).toEqual(false);

    wrapped.instance().setState({ uploading: true }, () => {
        wrapped.instance().forceUpdate();
        
        expect(uploadButton.prop("disabled")).toEqual(false);
        // This is supposed to fail, but it passes
    });
});
```This works

In your test assertion is never triggered because test runner never has a chance to wait until setState callback call: neither promise was returned from test not test finish callback was used.

SwinX avatar Nov 11 '19 14:11 SwinX

I'm having the same issue.

Doing wrapper.instance().forceUpdate() works for me but looking at the documentation I would expect wrapper.update() to do the same. I don't know how "safe" using forceUpdate is but for now it's fixed the problem for me.

Im not 100% sure but i think that:

Enzyme's update() method checks if props/state changed and based on that decides to update component or not.

forceUpdate() in this case is actually React's method. Notice that you don't call it at wrapper but at wrapper.instance(). It causes a re-render no matter what https://reactjs.org/docs/react-component.html#forceupdate.

I'd say that this is acceptable solution.

MrMuzyk avatar Nov 21 '19 10:11 MrMuzyk

forceUpdate won't work in a functional component though, as there is no instance

shaun-weddell avatar Dec 04 '19 07:12 shaun-weddell

@shaun-weddell - You're absolutely right. For React FC - the instance() method will return null. So, obviously we can't call forceUpdate()

nathan5x avatar Apr 30 '20 22:04 nathan5x

This code works for functional component:

    let component = mount(<test.component />);
    component.setProps({ foo: 42 }); // re-render

Actually, my component even don't need to have a prop foo.

PFight avatar Jun 25 '20 10:06 PFight

Following @PFight idea, this generic approach worked for me:

const component = mount(<YourComponent {...anyProps} />);
component.setProps(); // Forces react component tree to re-render.
component.update(); // Syncs the enzyme component tree snapshot with the react component tree.

lquixada avatar Jul 30 '20 00:07 lquixada

Actually, since setProps expect next props to merge, component.setProps() should be enough to trigger a re-render

mmassaki avatar Jul 31 '20 15:07 mmassaki

@mmassaki you're right! just fixed the suggestion! thanks!

lquixada avatar Jul 31 '20 16:07 lquixada

setProps fixed the problem for me but doesnt seem like a real solution

travisdahl avatar Aug 29 '20 03:08 travisdahl

.update isn't supposed to rerender. It's supposed to update the enzyme tree based on the latest state of the react tree.

In other words, if you haven't changed any props or state, there's nothing to rerender.

ljharb avatar Aug 29 '20 05:08 ljharb

in my particular case, its not the "rendering" i care about but its the only way I can get the new mock value to be recognized...

Note: in a beforeEach I am doing the shallow mounting and mocking my module for general use.

in this test I want to mock a different return value. if i dont force the rerender with wrapper.setProps() it never uses this new mock value, but instead the one from the before each.

...

  let wrapper;
  let props;

  beforeEach(() => {
    myMockModule = jest.fn().mockReturnValue({
      fizz: 'buzz',
    });

    wrapper = shallow(<App  />);
  });

 ...


    test('my test', () => {
      myMockModule.mockReturnValueOnce({
        foo: 'bar',
      });
      wrapper.setProps(); // without this it doesnt work
      expect(wrapper).toMatchSnapshot();
    });

travisdahl avatar Aug 29 '20 06:08 travisdahl

What do you mean the new mock value? All mocks should be done before creating the wrapper.

It makes no sense whatsoever to call shallow in a beforeEach. Repetition in tests is good.

ljharb avatar Aug 29 '20 06:08 ljharb

hmmm interesting.... Ive written a few thousand tests set up like that. 🤣 my bad.

i usually do a shallow in the before each and then set props and state in each test and assert im getting the desired results. gets rid of a lot of boiler plate and ensures I always get a fresh render. why does it "makes no sense whatsoever"? It seems like it is repetition, just automatic? i.e. what is the problem in doing it in a beforeEach if you are gonna do it at the beginning of every test anyway? I'd love to hear more about it, but dont want to hijack this thread either.

travisdahl avatar Aug 29 '20 06:08 travisdahl

The difference is that each test that has a tiny modification can change it without shenanigans like "oops, let me update the wrapper and rerender it", and that failure messages are clearer.

ljharb avatar Aug 29 '20 06:08 ljharb

yes, i guess my code snippet above proves your point. If i was mocking before i created the wrapper in each test I wouldnt have the problem I do. Thanks!

The crazy part is the setProps actually does fix it though and let me re-mock the value. Maybe just a happy side-effect

travisdahl avatar Aug 29 '20 07:08 travisdahl