【问题标题】:How to mock component method using Jest and Enzyme如何使用 Jest 和 Enzyme 模拟组件方法
【发布时间】:2018-03-27 23:12:57
【问题描述】:

我有一个 React 组件,它有一个文本 input 作为主包装器内的子组件之一。当input 获得焦点时,它会通过其onFocus 属性调用一个函数。所以组件的结构是这样的:

<div className="main-wrapper"> <input type="text" onFocus={this.focusHandler} /> </div>

在类的其他地方有一个名为focusHandler 的方法,看起来像这样

focusHandler = () => { //Do whatever it is that focus handlers do. //In this case that involves changing the local state, so there is something like this.setState({ fieldHasFocus: true }); }

我想做的是进行一个测试(在 Jest 中),以验证当输入获得焦点时调用 focusHandler() 方法。但是,我不知道如何在 focusHandler() 的测试中添加一个模拟,并检查当我在输入字段上 simulate('focus') 时是否调用了它。

【问题讨论】:

  • 为什么要模拟这个而不是在simulate('focus')之后测试组件的状态
  • @AndreasKöberle 这是我自己的一个问题。是测试动作的直接结果是否发生更好,在这种情况下focusHandler()被调用,或者该动作的结果是否发生,在这种情况下状态被改变?还是同时测试两者更好?似乎测试动作的直接结果应该更重要,因为状态可能会被其他东西改变。那么也许应该编写第二个测试来查看调用函数时状态是否发生变化?或者这有点矫枉过正?

标签: reactjs unit-testing jestjs enzyme


【解决方案1】:

您可以在渲染组件之前查看。您不需要强制更新组件的实例。在您的 spec/describe 块之前的文件顶部声明 spy 函数。

const focusHandlerSpy = jest.spyOn(YourComponent.prototype, 'focusHandler');

然后……

describe('When the input field is focused', () => {
  beforeEach(() => {
    component.find('input').simulate('focus');
  });

  it('should invoke the focusHandlerSpy function', () => {
    expect(focusHandlerSpy).toHaveBeenCalled();
  });
});

【讨论】:

  • 它给出了这个错误:Cannot spyOn on a original value;给定的未定义
【解决方案2】:

试试这样的:

const wrapper = shallow(<YourComponent />);
const focusHandlerSpy = jest.spyOn(wrapper.instance(), 'focusHandler');
wrapper.instance().forceUpdate();

现在您的focusHandlerSpy 将被称为焦点。

【讨论】:

    猜你喜欢
    • 2017-05-18
    • 2017-12-18
    • 1970-01-01
    • 2019-10-27
    • 2019-01-29
    • 2017-06-09
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    相关资源
    最近更新 更多