我有一个包含以下道具和方法的组件:
class OrderDish extends Component {
static propTypes = {
order: React.PropTypes.object.isRequired,
addCommentToOrder: React.PropTypes.func,
};
handleCommentChange = (event) => {
this.props.addCommentToOrder(event.target.value, this.props.order, false);
};
render() {
const { order, canOrder } = this.props;
return (
<div className="Order-dish">
<TextField
className='Order-dish-comment'
ref="comment"
id={order.entry.type}
value={order.comment ? order.comment : ''}
onChange={this.handleCommentChange}
fullWidth
onKeyDown={this.handleKeyPress}
disabled={!canOrder}
/>
</div>
)
}
}
export default OrderDish;
现在我想测试handleCommentChange
事件在onChange
上触发时,使用正确的参数调用TextField
函数。
我对方法本身进行了单独的测试,它按预期工作:
it('handleCommentChange should call addCommentToOrder passing event.target.value, this.props.order, false', () => {
const mockKeyPressFN = jest.fn((input) => {return input});
let orderDish = shallow(<OrderDish order={mockOrder} addCommentToOrder={mockKeyPressFN}/>);
orderDish.instance().handleCommentChange({key: 'Enter', target: {value: 'mock'}});
expect(mockKeyPressFN.mock.calls[0]).toContainEqual("mock", {"entry": {"name": "blah", "tag": "MAIN", "type": "bleh"}, "price": 5.44}, false);
});
现在当我尝试对simulate做同样的事情时(传递模拟对象,看看函数是否被调用):
it('TextField should call handleCommentChange onChange', ()=> {
const mockKeyPressFN = jest.fn();
let orderDish = shallow(<OrderDish order={mockOrder} addCommentToOrder={mockKeyPressFN}/>);
let textField = orderDish.find('TextField');
let event = {key: 'Enter', target: {value: 'mock'}};
textField.simulate('change',[event]);
expect(mockKeyPressFN.mock.calls.length).toBe(1);
});
我明白了:
无法读取未定义的属性“值”
所以我猜我的event
对象没有正确传递给.simulate
函数?
我做错了什么?
答案 0 :(得分:0)
您需要摆脱阵列。
textField.simulate('change',[event]);
将是
textField.simulate('change',event);
另一种方法是:
act(() => {
orderDish.find('TextField').simulate('change', {key: 'Enter', target: {value: 'mock'}}, other_arguments_to_handleCommentChange);
orderDish.update();
});