【问题标题】:Unable to test click : error method ''simulate'' is meant to run on 1 node无法测试点击:错误方法“模拟”意味着在 1 个节点上运行
【发布时间】:2019-07-20 10:42:25
【问题描述】:

我能够在这个文件上测试一些 onClick 事件,但是当涉及到下面的代码时,我无法测试。 我相信的主要原因是因为 render 中有一个类我无法对其进行测试

我尝试通过 className、id 等进行测试。但仍然遇到同样的错误。

使用 jest 和酶 - React JS

这是我要测试的 onClick 事件:

         <div className='report-wrapper'>

        <div className='fields-item-wrapper span-two-col'>
          <label className='workflow-label' for=''> Contacts </label>
          <Select
            className={'field-input-select margin-right'}              
            id=''
            value={this.state.Contact}
            onChange={(e) => {let val = e ? e.value : null; this.setState({Contact: e, Account: null, accountOptions: []}); this.getAccounts(e)}}
            onClick={() => {this.setState({showRequired: false})} }
            options={this.state.contactOptions}
            isDisabled={loading}
          />
        </div>

使用 jest 和酶 - 我已经安装了组件

describe(' Edit Data Test', () => {
 let wrapper;

  beforeEach(() => wrapper = mount(<BrowserRouter><Component {...baseProps} /></BrowserRouter>));

it("should check button click event - Select class", () => {
baseProps.onClick.mockClear();
wrapper.setState({
  showRequired: false,
});
wrapper.update() 
wrapper.find('#test').simulate("click");

  });

【问题讨论】:

  • 什么是'#test'?听起来好像没有找到你的元素....
  • 以前是 id=' ' ,我添加了 test 只是为了尝试找到 id 但它没有找到元素
  • 那么通过标签或者类名选择select元素?
  • 我通常通过类名或id进行测试,但找不到。此选择位于 render() 内
  • @epascarello 有什么线索吗?

标签: javascript reactjs onclick jestjs enzyme


【解决方案1】:

原来你在被测试的组件上使用了withRouter。基本上,访问封装在 HOC 中的组件比您尝试做的要复杂一些。

首先,我建议阅读我在Medium 上的文章,以便对新出现的问题有一个基本的了解。让我强调一下我从那里抓取的以下句子:

实际的问题是您不能直接访问 HOC 中的组件,而是必须从更深层次获取适当的组件。

其次,您应该像这样更改组件的安装:

// Imports ...

describe('something', () => {
   let wrapper;

   beforeEach(() => {
      // This can be used to do full DOM rendering: mount(shallow(<MyComponent />).get(0));
      wrapper = shallow(shallow(<MyComponent />).get(0)); 
      // Notice that I don't use <BrowserRouter />. Obviously, pass the necessary props to the component.
   });

   it('tests something', () => {
      // I don't know exactly what `baseProps` is in your code, probably you don't need that here.
      // What you need to do is find the corresponding component and simulate a click event.
      wrapper.find(Select).simulate('click');

      // And here, write the expected action which probably should be the same as it is in your case:
      expect(wrapper.state('showRequired')).toBeFalsy();
   });
});

请下次提供有关代码、结构和实际问题的更准确信息。此外,您在上面添加的示例中的缩进非常糟糕,很难理解那里实际发生了什么。

【讨论】:

  • 感谢您的帮助,是的,我下次会修复我的缩进
猜你喜欢
  • 1970-01-01
  • 2019-07-14
  • 2019-07-20
  • 2021-03-09
  • 2020-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多