How to unit test a method of react component?

110.1k views Asked by At

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
3

There are 3 answers

5
Swapnil On BEST ANSWER

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

1
Or A. On

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

0
captain-yossarian from Ukraine On

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