Reputation: 10052
I have a component with the following method that calls a function set via props:
class OrderDish extends Component {
static propTypes = {
image: React.PropTypes.any,
order: React.PropTypes.object.isRequired,
removeFromOrder: React.PropTypes.func,
addCommentToOrder: React.PropTypes.func,
canOrder: React.PropTypes.bool
};
handleKeyPress = (e) => {
if (e.key === 'Enter') {
this.props.addCommentToOrder(e.target.value, this.props.order, true);
}
};
render() {
const { order, canOrder } = this.props;
return (
<div className="Order-dish">
<div className="Order">
<div className="Order-extra-info">
<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>
</div>
</div>
)
}
}
export default OrderDish;
Now the first thing that I would like to test is the method itself - if I pass in the key: 'Enter'
, will it try to call the addCommentToOrder
prop?
So I made a mock function with jest that returns true, and tried to pass it as a prop, then call the method and see what happens:
it('Test field should call handleKeyPress on key down', () => {
const mockKeyPressFN = jest.fn(() => { return true; });
let orderDish = shallow(<OrderDish order={mockOrder} addCommentToOrder={mockKeyPressFN}/>);
expect(orderDish.instance().handleKeyPress({key: 'Enter', target: {value: 'mock'}})).toBe(true);
});
But my test fails with the following output:
expect(received).toBe(expected) Expected value to be (using ===): true Received: undefined
console.log(orderDish.instance());
Returns the method as a function:
handleKeyPress: [Function]
This:
console.log(orderDish.instance().handleKeyPress({key: 'Enter', target:{value: 'mock'}}));
Does not log anything.
What am I doing wrong?
Upvotes: 1
Views: 1137
Reputation: 1017
expect(orderDish.instance().handleKeyPress({key: 'Enter', target: {value: 'mock'}})).toBe(true);
You are testing handleKeyPress()'s return value, but the function doesn't return anything.
It's mockKeyPressFN that is returning a value, and presumably what you want to test.
You can test the return value, or the fact that it was called, or both - https://facebook.github.io/jest/docs/mock-functions.html
for example:
expect(mockKeyPressFN.mock.calls.length).toBe(1);
Upvotes: 1