36

I am testing a keybinding feature in a component. The component is rather simple, event listener for the keyup and fires up a redux action which will hide the component.

I have cleaned up my code here to only relevant information. I am able to make the test pass if I just use the store dispatch to make the action call but that of course will defeat the purpose of this test. I am using Enzyme to simulate the keyup event with the appropriate event data (keycode for esc) but I come across the error below.

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);
  });
});

Errors:

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)

4 Answers 4

56

That error happens when, as it says, you run it with any number of nodes other than 1.

Similar to jQuery, your find call will return some number of nodes (really it's a single wrapper that knows how many nodes your find selector has found). And you can't call simulate against 0 nodes! Or multiple.

The solution then is to figure out why your selector (the styles.container in wrapper.find(styles.container)) is returning 0 nodes, and make sure it returns exactly 1, and then simulate will work as you expect.

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's debug method is really useful here. You could do console.log(container.debug()), or also console.log(container.html()) to make sure your component is rendering as expected during the test.

1
  • Nothing display console.log(container.debug()). display blank because I append static string. @tyler-collier Aug 17, 2022 at 5:48
4

You don't find any node because the element that you try to reach is in another level. Select a specific element by the class, id.. and try this

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

If you have more than one HTML elements like

 <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> 

and are calling it by a generic query like

wrapper.find('button').simulate('click');

it will return all the three nodes for you. So call it by unique ID's or ClassNames.

0

Hi guys in my case I use 1-first get the container 2- get the button 3- execute the prop 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()
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.