有没有办法在React组件的胖箭头类实例方法上使用Jest进行间谍/模拟?

时间:2018-02-26 23:46:57

标签: reactjs jestjs enzyme

我有一个handleClick功能:

handleClick = tagIndex => {
    console.log(tagIndex)
    if (tagIndex >= 0 && tagIndex < this.state.suggestedTags.length)
        this.state.suggestedTags.splice(tagIndex, 1);
} 

在我的React类中,我无法正确地模拟或监视它。

我正在尝试这个

it('should call handleClick when a tag is clicked', () => {
        wrapper.setState({ suggestedTags: ['Mozart'] })
        const spy = jest.spyOn(component, 'handleClick')
        component.forceUpdate()
        wrapper.find('.suggested-tags__item').simulate('click')
        expect(spy).toHaveBeenCalled()
    })

但我得到的只是Expected mock function to have been called

1 个答案:

答案 0 :(得分:1)

const spy = jest.spyOn(component, 'handleClick')
wrapper.instance().forceUpdate(); // Here is the difference
wrapper.find('.suggested-tags__item').simulate('click')
expect(spy).toHaveBeenCalled()

https://github.com/airbnb/enzyme/issues/365