功能组件-模拟方法或useRef

时间:2019-11-28 08:58:17

标签: reactjs typescript jestjs enzyme

我有一个功能组件,它使用一种方法来滚动到某个div(通过ref),因此非常简化,就像这样:

import React, {useRef} from 'react';

export const DummyComponent: React.FC = props => {
   const divRef = useRef<HTMLDivElement>();

   const scrollToDiv = () => divRef.current.scrollTo();

   return (
      <div ref={divRef} />
         <button onClick={scrollToDiv}>scroll</button>
      </div>
   );
}

我想模拟按钮单击,但是错误消息是Error: Uncaught [TypeError: divRef.current.scrollTo is not a function]

到目前为止我在测试中尝试过的内容(Series.mul):

import React from 'react';
import { mount, ReactWrapper } from 'enzyme';
import {DummyComponent} from "./DummyComponent";

let wrapper: ReactWrapper;

describe('test', () => {
    beforeEach(() => {
        wrapper = mount(<DummyComponent/>);
    });

    test('simulate', () => {
        /* despite the spyOn, when I debug the ref is actually holding the div - scrollTo is not working though */
        jest.spyOn(React, 'useRef').mockReturnValue({current: {scrollTo: jest.fn()}});
        /* this also has no effect */
        jest.mock('./DummyComponent', () => ({
            scrollToTop: jest.fn()
        }));
        wrapper.find('button').simulate('click');
    });
});

我们将不胜感激任何帮助或提示。

1 个答案:

答案 0 :(得分:0)

我设法以一种通用的方式嘲笑Bearer TOKEN,在这里Mocking refs in React function component