componentDidMount 是否应该在 Enzyme 中以浅层渲染运行?

IT技术 javascript reactjs unit-testing enzyme
2021-05-16 13:17:14

根据我的理解以及迄今为止我在各种答案中阅读的内容,并非所有生命周期方法都应该使用浅层渲染运行。尤其componentDidMount

但是,我注意到当我这样做时

  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);
  });

测试通过。

那么,我在这里做错了什么还是我理解错了?

以供参考

1个回答

是的,它在enzyme 3.0.

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

LifeCycleExperimental这以前是您必须手动设置为 true 的选项,shallow现在默认启用,因为它现在很稳定。

这比mount在想要测试生命周期时不得不求助要好得多

现在绝对没有理由不shallow用于单元测试 :)... 除了需要测试 refs 时 :(。