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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47309585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:18:11  来源:igfitidea点击:

Is componentDidMount supposed to run with shallow rendering in Enzyme?

javascriptreactjsunit-testingenzyme

提问by Dimitris Karagiannis

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

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

以供参考

回答by Martin Dawson

Yes it is in enzyme 3.0.

是的,它在enzyme 3.0.

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

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

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

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

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

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

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

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