我有一个React组件,我试图测试它的一些实例方法,但我很难理解我应该怎么做。绊倒我的问题是,我在测试中指的是this.setState()
,而且在我的测试中指的是event.target
,因此返回undefined
。处理这个问题的正确方法是什么?
这是我的组件:
export default class MessageForm extends Component {
constructor(props) {
super(props);
this.state = {
message: '',
};
}
onChange(event) { // testing this method
const message = event.target.value; // event is undefined
this.setState(prevState => Object.assign({}, prevState, { message })); // 'this' is undefined
}
handleOnClick(event) {
event.preventDefault();
// do some stuff here
}
render() {
return (
<Form action="post">
<TextArea onChange={this.onChange} />
<ExpireButtonGroup />
<SubmitButton onClick={this.handleOnClick}>
<LockIcon src={lock} />
Save
</SubmitButton>
</Form>
);
}
}
我正在使用Jest和Enzyme进行测试。我能够使用此测试触发该方法:
test('it should allow a message to be typed', () => {
const messageForm = shallow(<MessageForm />);
expect(messageForm.instance().onChange())
});
----------- ----------- EDIT
我发现了这个问题:How to mock React component methods with jest and enzyme
......这似乎有所帮助,但我仍然坚持错误cannot read property 'target' of undefined
。这是我的新测试:
test('it should handle a click event', () => {
const mockEvent = {
target: { dataset: { value: '60' }}
};
const button = shallow(<ExpireButton value={40}>Save</ExpireButton>);
button.instance().handleOnClick(mockEvent) = jest.fn();
button.update();
button.simulate('click');
expect(button.handleOnClick).toBeCalled();
});
});
答案 0 :(得分:2)
你几乎做到了。在实例中,只需根据需要发送参数。
test('it should allow a message to be typed', () => {
const messageForm = shallow(<MessageForm />);
expect(messageForm.instance().onChange({target:"any text you want"}))
});