在 React 函数组件中模拟 refs

Sha*_*uch 5 reactjs jestjs enzyme react-hooks

我有一个 React 函数组件,它在它的一个子组件上有一个引用。ref 是通过useRef.

我想用浅渲染器测试组件。我必须以某种方式模拟 ref 来测试其余的功能。

我似乎找不到任何方法来获得这个 ref 并嘲笑它。我尝试过的事情

  • 通过 childs 属性访问它。React 不喜欢那样,因为 ref 并不是真正的道具

  • 模拟 useRef. 我尝试了多种方法,但只有在我的实现使用时才能让它与间谍一起工作React.useRef

我看不到任何其他方式可以让裁判嘲笑它。在这种情况下我必须使用 mount 吗?

我无法发布真实场景,但我构建了一个小示例

it('should test', () => {
    const mock = jest.fn();
    const component = shallow(<Comp onHandle={mock}/>);


    // @ts-ignore
    component.find('button').invoke('onClick')();

    expect(mock).toHaveBeenCalled();
});

const Comp = ({onHandle}: any) => {
    const ref = useRef(null);

    const handleClick = () => {
        if (!ref.current) return;

        onHandle();
    };

    return (<button ref={ref} onClick={handleClick}>test</button>);
};
Run Code Online (Sandbox Code Playgroud)

sli*_*wp2 10

这是我的单元测试策略,jest.spyOnuseRef钩子上使用方法间谍。

index.tsx

import React from 'react';

export const Comp = ({ onHandle }: any) => {
  const ref = React.useRef(null);

  const handleClick = () => {
    if (!ref.current) return;

    onHandle();
  };

  return (
    <button ref={ref} onClick={handleClick}>
      test
    </button>
  );
};
Run Code Online (Sandbox Code Playgroud)

index.spec.tsx

import React from 'react';
import { shallow } from 'enzyme';
import { Comp } from './';

describe('Comp', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  it('should do nothing if ref does not exist', () => {
    const useRefSpy = jest.spyOn(React, 'useRef').mockReturnValueOnce({ current: null });
    const component = shallow(<Comp></Comp>);
    component.find('button').simulate('click');
    expect(useRefSpy).toBeCalledWith(null);
  });

  it('should handle click', () => {
    const useRefSpy = jest.spyOn(React, 'useRef').mockReturnValueOnce({ current: document.createElement('button') });
    const mock = jest.fn();
    const component = shallow(<Comp onHandle={mock}></Comp>);
    component.find('button').simulate('click');
    expect(useRefSpy).toBeCalledWith(null);
    expect(mock).toBeCalledTimes(1);
  });
});
Run Code Online (Sandbox Code Playgroud)

100% 覆盖率的单元测试结果:

 PASS  src/stackoverflow/57805917/index.spec.tsx
  Comp
    ? should do nothing if ref does not exist (16ms)
    ? should handle click (3ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |      100 |      100 |      100 |      100 |                   |
 index.tsx |      100 |      100 |      100 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        4.787s, estimated 11s
Run Code Online (Sandbox Code Playgroud)

源代码:https : //github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/57805917

  • 如果组件有多个 useRef 怎么办? (3认同)

alm*_*man 8

Slideshowp2 的解决方案对我不起作用,因此最终使用了不同的方法:

解决这个问题的方法是

  1. 引入一个 useRef 可选属性,默认情况下使用 React 的一个
import React, { useRef as defaultUseRef } from 'react'
const component = ({ useRef = defaultUseRef }) => {
  const ref = useRef(null)
  return <RefComponent ref={ref} />
}
Run Code Online (Sandbox Code Playgroud)
  1. 在测试模拟中 useRef
const mockUseRef = (obj: any) => () => Object.defineProperty({}, 'current', {
  get: () => obj,
  set: () => {}
})

// in your test
...
    const useRef = mockUseRef({ refFunction: jest.fn() })
    render(
      <ScanBarcodeView onScan={handleScan} useRef={useRef} />,
    )
...
Run Code Online (Sandbox Code Playgroud)


小智 6

如果您ref在组件的嵌套钩子中使用,并且始终需要某个current值,而不仅仅是第一个渲染器。您可以在测试中使用以下选项:

const reference = { current: null };
Object.defineProperty(reference, "current", {
    get: jest.fn(() => null),
    set: jest.fn(() => null),
});
const useReferenceSpy = jest.spyOn(React, "useRef").mockReturnValue(reference);
Run Code Online (Sandbox Code Playgroud)

并且不要忘记useRef在组件中写入如下内容

const ref = React.useRef(null)
Run Code Online (Sandbox Code Playgroud)