Error: This method is only meant to be run on single node. 0 found instead

Error: This method is only meant to be run on single node. 0 found instead

我正在测试组件中的键绑定功能。该组件相当简单,keyup 的事件侦听器并启动 redux 操作 将隐藏该组件。

我已经清理了这里的代码,只留下相关信息。如果我只使用 store dispatch 进行操作调用,我能够使测试通过,但这当然会破坏此测试的目的。我正在使用 Enzyme 使用适当的事件数据(esc 的键码)模拟 keyup 事件,但我遇到了以下错误。

MyComponent.js

import React, {Component, PropTypes} from 'react';
import styles from './LoginForm.scss';
import {hideComponent} from '../../actions';
import {connect} from 'react-redux';

class MyComponent extends Component {
  static propTypes = {
      // props
  };

  componentDidMount() {
    window.addEventListener('keyup', this.keybindingClose);
  }

  componentWillUnmount() {
    window.removeEventListener('keyup', this.keybindingClose);
  }
  
  keybindingClose = (e) => {
    if (e.keyCode === 27) {
      this.toggleView();
    }
  };

  toggleView = () => {
    this.props.dispatch(hideComponent());
  };

  render() {
    return (
      <div className={styles.container}>
        // render code
      </div>
    );
  }
}

export default connect(state => ({
  // code
}))(MyComponent);

MyComponent-test.js

import React from 'react';
import chai, {expect} from 'chai';
import chaiEnzyme from 'chai-enzyme';
import configureStore from 'redux-mock-store';
import {mount} from 'enzyme';
import {Provider} from 'react-redux';
import thunk from 'redux-thunk';
import {MyComponent} from '../../common/components';
import styles from '../../common/components/MyComponent/MyComponent.scss';

const mockStore = configureStore([thunk]);
let store;
chai.use(chaiEnzyme());

describe.only('<MyComponent/>', () => {
  beforeEach(() => {
    store = mockStore({});
  });

  afterEach(() => {
    store.clearActions();
  });

  it('when esc is pressed HIDE_COMPONENT action reducer is returned', () => {
    const props = {
      // required props for MyComponent
    };
    const expectedAction = {
      type: require('../../common/constants/action-types').HIDE_COMPONENT
    };
    const wrapper = mount(
      <Provider store={store} key="provider">
        <LoginForm {...props}/>
      </Provider>
      );
    // the dispatch function below will make the test pass but of course it is not testing the keybinding as I wish to do so
    // store.dispatch(require('../../common/actions').hideComponent());
    wrapper.find(styles.container).simulate('keyup', {keyCode: 27});
    expect(store.getActions()[0]).to.deep.equal(expectedAction);
  });
});

错误:

Error: This method is only meant to be run on single node. 0 found instead. 

at ReactWrapper.single (/Users/[name]/repos/[repoName]/webpack/test.config.js:5454:18 <- webpack:///~/enzyme/build/ReactWrapper.js:1099:0)
        

at ReactWrapper.simulate (/Users/[name]/repos/[repoName]/webpack/test.config.js:4886:15 <- webpack:///~/enzyme/build/ReactWrapper.js:531:0)


at Context.<anonymous> (/Users/[name]/repos/[repoName]/webpack/test.config.js:162808:55 <- webpack:///src/test/components/MyComponent-test.js:39:40)

当您 运行 它与除 1 以外的任意数量的节点时,就会发生该错误。

类似于 jQuery,您的 find 调用将 return 一些节点(实际上它是一个包装器,知道您的 find 选择器找到了多少节点).而且你不能对 0 个节点调用 simulate!或多个。

然后解决方案是弄清楚为什么你的选择器(wrapper.find(styles.container) 中的 styles.container)是 returning 0 个节点,并确保它 return 是正确的1,然后 simulate 将如您所愿地工作。

const container = wrapper.find(styles.container)
expect(container.length).to.equal(1)
container.simulate('keyup', {keyCode: 27});
expect(store.getActions()[0]).to.deep.equal(expectedAction);

Enzyme 的debug 方法在这里非常有用。您可以 console.log(container.debug())console.log(container.html()) 来确保您的组件在测试期间按预期呈现。

如果您有多个 HTML 个元素,例如

 <button className = "age_up" onClick = {() => dispatch(onAgeUpAction())}> 
        Age UP 
        </button> 
        <button className = "age_down" onClick = {() => dispatch(onAgeDownAction())}>
             Age Down 
       </button> 
        <button type = "button"onClick = {handleClick}> 
        Fetch Post 
        </button> 

并通过像

这样的通用查询来调用它
wrapper.find('button').simulate('click');

它将return 为您提供所有三个节点。 所以通过唯一 ID 或类名来调用它。

您没有找到任何节点,因为您尝试到达的元素在另一个级别。 Select class 的特定元素,id.. 然后试试这个

wrapper.find('LoginForm')
  .dive()
  .find('.CLASS_NAME_OF_ELEMENT')
  .simulate('click');

大家好,我用的是 1-首先获取容器 2-获取按钮 3- 执行 onClick

道具
 it('should Click on edit row', () => {
  const containerButton =  wrapper.find('.editCell')
  const editButton = containerButton.find('.buttonAlignRight')  
  editButton.props().onClick() 
  expect(wrapper.find('input')).toBeVisible()
})