我正在使用Jest来测试以下Material-UI组件。我想声明在单击RaisedButton组件时调用函数handleSubmit。
//Form.js
export default class Form extends React.Component {
<RaisedButton
ref="buttonTag"
className='SubmitButton'
label='Go'
icon={<ActionSearch />}
onClick={this.handleSubmit} />
handleSubmit = (event) => {
};
}
//Form-test.js
import Form from '../../src/Components/Form/Form';
import React from 'react';
import TestUtils from 'react-dom/test-utils';
let form = TestUtils.renderIntoDocument(
<Form />
);
const spy = jest.spyOn(form, 'handleSubmit').mockImplementation(() => {});
let buttonNode = form.refs.buttonTag;
TestUtils.Simulate.click(buttonNode);
expect(spy).toHaveBeenCalled();
执行时:
TestUtils.Simulate.click(buttonNode);
我收到以下错误:
"Cannot read property '__reactInternalInstance$a2hlbpvzpyeu9ywvcwjr1kyb9' of undefined"
如何正确模拟RaisedButton上的点击以触发handleSubmit()?
答案 0 :(得分:0)
而不是:
let buttonNode = form.refs.buttonTag;
我是如何解决这个问题的,就是在按钮上放一个普通的ID="myID"
,然后就这样得到它:
const buttonNode = document.getElementById("myID");
然后执行TestUtils.Simulate.click(buttonNode);