unit testing - Why do I get method is not a function in my jesttest? -
my jest unittest looks this:
import react 'react'; import renderer 'react-test-renderer'; import reacttestutils 'react-dom/test-utils' import calculator "./calculator"; test('test calculator', () => { const component = renderer.create( <calculator></calculator> ); let tree = component.tojson(); expect(tree).tomatchsnapshot(); console.log('component=',component.refs); // simulate click on button -> trigger sumcalc() reacttestutils.simulate.click(component.refs.button); });
when run test get:
typeerror: cannot read property 'button' of undefined
my react component looks this:
import react, {component} 'react'; export default class calculator extends component { constructor(props) { super(props); this.calcsum = this.calcsum.bind(this); this.state = {sum: 0}; } calcsum() { console.log('this.refs.one=', this.refs.one); let s = number(this.refs.one.value) + number(this.refs.two.value); this.setstate({sum: s}); } render() { return (<div> <input type="text" placeholder="number 1" ref="one"/> <input type="text" placeholder="number 2" ref="two"/> <button ref="button" onclick={this.calcsum}>sum</button> sum: {this.state.sum} </div> ); } }
how can avoid error? missing? component works when rendered dom unit test has issues.
component.tojson()
returns json not javascript object. calcsum
not prop, instead method defined on component class.
hence use getinstance()
method manually invoke calcsum
.
try this:
const component = renderer.create(<calculator />); component.getinstance().calcsum();
now can see console.log
output calcsum
.
Comments
Post a Comment