使用 enzyme shallow - function returns undefined 而不是 true 测试 ReactJS 组件方法

Testing ReactJS component methods with enzyme shallow - function returns undefined instead of true

我有一个具有以下方法的组件,它通过 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 prop 吗?

所以我做了一个 mock function with jest that returns true, and tried to pass it as a prop, then 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());

Returns 作为函数的方法:

handleKeyPress: [Function]

这个:

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

不记录任何内容。

我做错了什么?

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

您正在测试 handleKeyPress() 的 return 值,但该函数没有 return 任何东西。

mockKeyPressFN 正在 returning 一个值,大概是您要测试的值。

您可以测试 return 值,或它被调用的事实,或两者 - https://facebook.github.io/jest/docs/mock-functions.html

例如:

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