Jest spyOn function called

前端 未结 3 1361
栀梦
栀梦 2020-12-02 09:42

I\'m trying to write a simple test for a simple React component, and I want to use Jest to confirm that a function has been called when I simulate a click with enzyme. Accor

3条回答
  •  [愿得一人]
    2020-12-02 10:20

    You're almost there. Although I agree with @Alex Young answer about using props for that, you simply need a reference to the instance before trying to spy on the method.

    describe('my sweet test', () => {
     it('clicks it', () => {
        const app = shallow()
        const instance = app.instance()
        const spy = jest.spyOn(instance, 'myClickFunc')
    
        instance.forceUpdate();    
    
        const p = app.find('.App-intro')
        p.simulate('click')
        expect(spy).toHaveBeenCalled()
     })
    })
    

    Docs: http://airbnb.io/enzyme/docs/api/ShallowWrapper/instance.html

提交回复
热议问题