在 React with Enzyme 中测试去抖动方法

Vad*_*hyn 5 lodash reactjs jestjs enzyme

//Component
import _ from 'lodash';

constructor(props) {
  super(props);
  this.onScroll = _.debounce(::this.onScroll, 100);
}

onScroll() {
  //some code
}

//Test
it('onScroll', () => {
  const component = shallow(<Component />);
  component.instance().onScroll(); //Dosn't call method 
})
Run Code Online (Sandbox Code Playgroud)

我将酶用于渲染组件,将 lodash 用于debounce. 怎么打电话component.instance().onScroll()

Den*_*nge 1

您可以返回一个承诺并在其中断言。

it('onScroll', () => {
    const component = shallow(<Component />);
    return new Promise(resolve=> {
       component.instance().onScroll();
       expect(mockOnScrollFunction).toHaveBeenCalledTimes(1);
       setTimeout(resolve,101);
   }
}
Run Code Online (Sandbox Code Playgroud)