用酶浅 - 函数测试ReactJS组件方法返回undefined而不是true

时间:2017-01-10 11:28:04

标签: reactjs jestjs enzyme

我有一个带有以下方法的组件,它通过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;

现在我要测试的第一件事就是方法本身 - 如果我传入key: 'Enter',它会尝试调用addCommentToOrder道具吗?

所以我用jest做了一个mock function,返回true,并尝试将其作为道具传递,然后call the method看看会发生什么:

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);
  });

但我的测试失败了,输出如下:

expect(received).toBe(expected)

Expected value to be (using ===):
  true
Received:
  undefined
console.log(orderDish.instance());

将方法作为函数返回:

handleKeyPress: [Function]

此:

console.log(orderDish.instance().handleKeyPress({key: 'Enter', target:{value: 'mock'}}));

不记录任何内容。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

expect(orderDish.instance().handleKeyPress({key: 'Enter', target: {value: 'mock'}})).toBe(true);

您正在测试handleKeyPress()的返回值,但该函数不会返回任何内容。

它返回一个值的mockKeyPressFN,大概就是你要测试的内容。

您可以测试返回值,或者调用它的事实,或两者兼而有之 - https://facebook.github.io/jest/docs/mock-functions.html

例如:

expect(mockKeyPressFN.mock.calls.length).toBe(1);