首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Jest和Enzyme模拟组件方法

如何使用Jest和Enzyme模拟组件方法
EN

Stack Overflow用户
提问于 2018-03-28 07:12:57
回答 2查看 5.2K关注 0票数 1

我有一个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')操作时检查是否调用了模拟。

EN

回答 2

Stack Overflow用户

发布于 2018-03-28 18:59:07

您可以在呈现组件之前侦测。您不需要强制更新组件的实例。在spec/describe代码块之前,在文件的顶部声明间谍函数。

代码语言:javascript
复制
const focusHandlerSpy = jest.spyOn(YourComponent.prototype, 'focusHandler');

然后..。

代码语言:javascript
复制
describe('When the input field is focused', () => {
  beforeEach(() => {
    component.find('input').simulate('focus');
  });

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

Stack Overflow用户

发布于 2018-03-28 18:46:39

尝试如下所示:

代码语言:javascript
复制
const wrapper = shallow(<YourComponent />);
const focusHandlerSpy = jest.spyOn(wrapper.instance(), 'focusHandler');
wrapper.instance().forceUpdate();

现在,您的focusHandlerSpy将在focus上调用。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49523798

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档