V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
Jack0112
V2EX  ›  问与答

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

  •  1
     
  •   Jack0112 · May 23, 2020 · 1515 views
    This topic created in 2178 days ago, the information mentioned may be changed or developed.

    如题,举个例子:

    // 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的函数是否被调用?

    3 replies    2020-05-23 20:58:39 +08:00
    ayase252
        1
    ayase252  
       May 23, 2020 via iPhone
    expect(mockFunc).toHaveBeenCalled()
    你应该测的是你的 spy
    Jack0112
        2
    Jack0112  
    OP
       May 23, 2020
    @ayase252 怎么修改一下?能指点一下嘛?
    Jack0112
        3
    Jack0112  
    OP
       May 23, 2020
    @ayase252 不好意思,没仔细看,我试一试
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4732 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 10:03 · PVG 18:03 · LAX 03:03 · JFK 06:03
    ♥ Do have faith in what you're doing.