Is componentDidMount supposed to run with shallow rendering in Enzyme?

Dimitris Karagiannis picture Dimitris Karagiannis · Nov 15, 2017 · Viewed 11.2k times · Source

From my understanding and from what I have read so far in various answers, not all lifecycle methods are supposed to be run with shallow rendering. Especially componentDidMount

However, I notice that when I do

  beforeEach(function () {
    fakeComponentDidMount = sinon.stub(Component.prototype, 'componentDidMount');
    fakeComponentDidMount.callsFake(function () {});
    wrapper = shallow(<Component {...props} />);
  });

  afterEach(function () {
    fakeComponentDidMount.restore();
  });

  it('calls componentDidMount', function () {
    expect(fakeComponentDidMount.called).to.equal(true);
  });

the test passes.

So, am I doing something wrong here or have I understood something wrong?

For reference

Answer

Martin Dawson picture Martin Dawson · Nov 16, 2017

Yes it is in enzyme 3.0.

https://github.com/airbnb/enzyme/blob/master/CHANGELOG.md#300

LifeCycleExperimental which was previously an option that you had to manually set to true on shallow is now enabled by default because it is now stable.

This is much nicer than having to resort to mount when wanting to test lifecycles.

There is absolutely no excuse to not use shallow for unit tests now :)... Well apart from when you need to test refs :(.