我正在尝试对我的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
你快到了。只需更改您的期望:
expect(wrapper.instance().checkBoxChecked()).equals(true);
您可以通过此链接了解有关使用酶测试组分方法的更多信息。