【问题标题】:Jest/Enzyme | Test a function call in componentDidMount [duplicate]笑话/酶 |在 componentDidMount 中测试函数调用 [重复]
【发布时间】:2019-03-01 10:40:00
【问题描述】:

当你想测试一个函数被调用时该怎么做,在componentDidMount()React生命周期方法上。基本上组件代码如下所示:

  state = {
    randomStateToPopulate: []
  };

  // Test componentDidMount
  componentDidMount() {
    this.randomFunction();
  }

  randomFunction= () => {
    listRandomData().then(({ data }) => {
      this.setState({ randomStateToPopulate: data });
    });
  };

那么,你如何实际测试这个案例?

【问题讨论】:

  • 正如所写,测试此组件的唯一方法似乎是“白盒”,这意味着您将根据randomFunction 的状态编写一个断言(无论它是否已被调用,例如例如)或randomStateToPopulate(是否分配给data)。但是白盒测试的缺点是,如果您更改内部实现,测试可能会中断。如果你展示了你是如何使用randomStateToPopulate(例如,把它放到一个HTML列表中),你可以编写一个不受实现细节约束的测试。

标签: reactjs unit-testing jestjs es6-promise enzyme


【解决方案1】:

这是您要测试的案例场景。如果正在调用 componentDidMount,请检查它是否只被调用过一次,或者你想要的多次。

你的测试。 I have the explanation in comments below

    // Inside your general `Describe`
  let wrapper;
  const props = {
    // Your props goes here..
  };
  beforeEach(() => {
    wrapper = shallow(<YourComponent {...props} />);
  });

    it('should check `componentDidMount()`', () => {
      const instance = wrapper.instance(); // you assign your instance of the wrapper
      jest.spyOn(instance, 'randomFunction'); // You spy on the randomFunction
      instance.componentDidMount();
      expect(instance.randomFunction).toHaveBeenCalledTimes(1); // You check if the condition you want to match is correct.
    });

你可以抽象,这个案例做更复杂的事情,但它的基本要点是上面的。如果您有更详细或更好的解决方案,请发布。谢谢!!

【讨论】:

  • 这是正确的。您必须在测试用例中自己调用 componentDidMount()。
  • 在我的情况下instance 是null,无论我使用mount 还是shallow :(
  • @GregWoz 我得到了和你一样的结果。对我来说,看起来我有一个 ReactFragment 作为我的组件返回的父 html 标记。类似:“return (>)”,这把一切都搞砸了。我通过在实例上使用 Find 解决了这个问题 (instance.Find('MyComponent'))
猜你喜欢
  • 2018-06-21
  • 1970-01-01
  • 2019-04-05
  • 1970-01-01
  • 2020-06-19
  • 2020-06-14
  • 2018-08-24
  • 2021-09-07
  • 1970-01-01
相关资源
最近更新 更多