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

新手上路,请多包涵

我正在尝试对我的 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

原文由 bier hier 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 299
1 个回答

你快到了。只需将您的期望更改为:

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

您可以通过 此链接 了解有关使用酶测试组件方法的更多信息

原文由 Swapnil 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进