How to unit test a method of react component?

Unit TestingReactjsChaiEnzyme

Unit Testing Problem Overview


I am trying to unit test my reactjs component:

import React from 'react';
import Modal from 'react-modal';
import store from '../../../store'
import lodash from 'lodash'

export class AddToOrder extends React.Component {
  constructor(props) {
    super(props);
    this.state = {checked: false}
    //debugger
  }
  checkBoxChecked() {
    return true
  }
  render() {
    console.log('testing=this.props.id',this.props.id )
    return (
      <div className="order">
        <label>
          <input
            id={this.props.parent}
            checked={this.checkBoxChecked()}
            onChange={this.addToOrder.bind(this, this.props)}
            type="checkbox"/>
          Add to order
        </label>
      </div>
    )
  }
}

export default AddToOrder;

Just to get started I am already struggling to assert the checkBoxChecked method:

import React from 'react-native';
import {shallow} from 'enzyme';
import {AddToOrder} from '../app/components/buttons/addtoorder/addtoorder';
import {expect} from 'chai';
import {mount} from 'enzyme';
import jsdom from 'jsdom';
const doc = jsdom.jsdom('<!doctype html><html><body></body></html>')
global.document = doc
global.window = doc.defaultView

let props;
beforeEach(() => {
  props = {
    cart: {
      items: [{
        id: 100,
        price: 2000,
        name:'Docs'
      }]
    }
  };
});

describe('AddToOrder component', () => {
  it('should be handling checkboxChecked', () => {
    const wrapper = shallow(<AddToOrder {...props.cart} />);
    expect(wrapper.checkBoxChecked()).equals(true); //error appears here
  });
});


How can I unit test a method on the component? This is the error I am getting:

    TypeError: Cannot read property 'checked' of undefined

Unit Testing Solutions


Solution 1 - Unit Testing

You are almost there. Just change your expect to this:

expect(wrapper.instance().checkBoxChecked()).equals(true);

You can go through this link to know more about testing component methods using enzyme

Solution 2 - Unit Testing

For those who find the accepted answer as not working, try using .dive() on your shallow wrapper before using .instance():

expect(wrapper.dive().instance().somePrivateMethod()).toEqual(true);

Reference: Testing component methods with enzyme

Solution 3 - Unit Testing

Extend of previous answer. If you have connected component (Redux) , try next code :

 const store=configureStore();
  const context = { store };
   const wrapper = shallow(
      <MyComponent,
      { context },
    );
   const inst = wrapper.dive().instance();
   inst.myCustomMethod('hello');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionbier hierView Question on Stackoverflow
Solution 1 - Unit TestingSwapnilView Answer on Stackoverflow
Solution 2 - Unit TestingOr A.View Answer on Stackoverflow
Solution 3 - Unit Testingcaptain-yossarian from UkraineView Answer on Stackoverflow