如何使用 Jest/Enzyme 在反应组件中模拟来自 useContext() 的反应 'dispatch' 函数

How to mock react 'dispatch' function from useContext() in a react component using Jest/Enzyme

我正在尝试测试 dispatch 事件是否已从我的组件中的按钮触发。 dispatch 来自 useContent()。但是我收到错误 dispatch is not a function。任何人都可以 help/point 我在正确的方向吗?

import LoanListItem from './LoanListItem';
import LoansContext from './loansContext';

it('should dispatch an action on clicking button', () => {
        const mockDispatch = jest.fn();
        const TestComponent = () => (
            <LoansContext value={mockDispatch}>
                <LoanListItem {...mockProps} />
            </LoansContext>
        );
        
        const wrapper = shallow(<TestComponent />);
        wrapper.find(LoanListItem).dive().find('.button').simulate('click');
        expect(mockDispatch).toHaveBeenCalledWith({
            type: 'selectedLoan',
            payload: 1,
        });
    });

以及要测试的组件的精简版本。

const LoanListItem = (props) => {
    const { id, title } = props.loan;
    const dispatch = useContext(LoansContext);

    const clickHandler = () => {
        dispatch({ type: 'selectedLoan', payload: id });
    };

    return (
        <div>
            <h2>{title}</h2>
            <button onClick={clickHandler}>Invest</button>
        </div>
    );
};

问题是您的 TestComponent 没有使用 Provider,您应该这样解决:

const TestComponent = () => (
    <LoansContext.Provider value={mockDispatch}>
        <LoanListItem {...mockProps} />
    </LoansContext.Provider>
);

你也不应该使用 shallow 因为它不会遍历组件,用 mount 代替它。