Jest 如何测试在 A 函数中调用的 B 函数?

如题,举个例子:

// ListItem.tsx
interface Props {
    onTouchStart: (e: React.TouchEvent) => void;
}

const ListItem: React.FC<Props> = (props) => {
    const handleTouchStart = (e: React.TouchEvent) => {
        // 在组件内部函数调用传入的函数
        props.onTouchStart(e);
        // 执行一些其他操作
    }

    return <div onTouchStart={handleTouchStart}></div>;
}

export default ListItem;
// ListItem.test.tsx
import { createElement } from 'rax';
import renderer from 'rax-test-renderer';

it('Test ListItem TouchStart', () => {
    const mockFunc = jest.fn();
    const component = renderer.create(<ListItem onTouchStart={mockFunc} />)
    const tree = component.toJSON();
    tree.eventListeners.touchstart();
    // 报错
    expect(tree.eventListeners.touchstart).toHaveBeenCalled();
})
expect(received).toHaveBeenCalled()

    Matcher error: received value must be a mock or spy function

    Received has type:  function
    Received has value: [Function handleTouchStart]

怎么在测试用例中测试传入props的函数是否存在?
怎么在测试用例中测试传入props的函数是否被调用?

阅读 208
评论
    撰写回答

    登录后参与交流、获取后续更新提醒