【问题标题】:Enzyme call method酶调用法
【发布时间】:2016-12-30 14:46:50
【问题描述】:

假设我的 React 组件中有一个方法:

doSomething() {
    // method uses this.props and this.state
}

我想针对设置的不同道具和状态测试此方法。那我怎么称呼它? MyClass.prototype.doSomething 将调用该函数,但未设置 this.propsthis.state

【问题讨论】:

  • 那么当你用酶创建组件时,是什么阻止你只传递道具?

标签: javascript reactjs enzyme


【解决方案1】:

您可以使用酶的instance 函数来获取渲染组件的实例,并在其上调用方法。

const wrapper = shallow(<MyClass {...props} />) wrapper.instance().doSomething()

【讨论】:

  • 是的,这行得通。请记住,当您之后检查状态时,您应该检查wrapper,而不是wrapper.instance()
【解决方案2】:

假设你的 doSomething() 方法是 increaseByOne() ,它只是增加了 +1

describe('Calculator', () => {
  it('should update state by 1 on increaseByOne()', () => {
    const wrapper = shallow(<Calculator />);
    expect(wrapper.instance().state().score).toBe(0);
    wrapper.instance().increaseByOne();
    expect(wrapper.instance().state().score).toBe(1);
  });
});

要了解更多信息,您可以查看有关 state()Instance() docs 的文档

【讨论】:

    【解决方案3】:

    注意:下面的@Tyler's answer 是更好的解决方案

    您可以只使用apply 要使用的this 的值:

    // MyClass.prototype.doSomething() becomes
    
    var mockThis = { 
      props: { coolProp: 'coolValue1' }, 
      state: { coolStateKey: 'coolValue2' }
    };
    MyClass.prototype.doSomething.apply(mockThis);` 
    

    【讨论】:

    • 这不是一个真正合适的解决方案。 MyClass 现在永远脏了;未来对它的调用将具有模拟集。
    • @Kousha not of OP 正确设置了他的测试用例。例如:在 Jasmine 测试的 beforeEach 块中创建 MyClass 的新实例。
    猜你喜欢
    • 2018-09-12
    • 2019-01-12
    • 1970-01-01
    • 2021-09-24
    • 2019-06-28
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    相关资源
    最近更新 更多