How to unit test a method of react component?

bier hier picture bier hier · Dec 17, 2016 · Viewed 51.4k times · Source

I am trying to unit test my reactjs component:

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

Answer

Swapnil picture Swapnil · Dec 17, 2016

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