如何对反应组分的方法进行单元测试?

时间:2016-12-17 07:51:54

标签: unit-testing reactjs chai enzyme

我正在尝试对我的reactjs组件进行单元测试:

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;

刚开始我已经在努力断言checkBoxChecked方法:

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

```

如何在组件上单元测试方法?这是我得到的错误:

TypeError: Cannot read property 'checked' of undefined

3 个答案:

答案 0 :(得分:51)

你快到了。只要改变你对此的期望:

jdbc:mysql://localhost:3306/openfire?rewriteBatchedStatements=true&useUnicode=true

您可以通过this link了解有关使用酶

测试组分方法的更多信息

答案 1 :(得分:7)

对于那些发现接受的答案无效的人,请在使用.dive()之前先在浅层包装上使用.instance()

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

参考:Testing component methods with enzyme

答案 2 :(得分:0)

扩展先前的答案。 如果已连接组件(Redux),请尝试下一个代码:

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