如何用笑话/酶中的“当前”道具测试useRef

时间:2019-06-24 15:21:59

标签: reactjs jestjs enzyme

我希望有人可以向我指出正确的方向,以便在下面的组件中测试useRef。

我有一个结构如下的组件。我正在尝试测试otherFunction()中的功能,但不确定如何模拟来自组件引用的当前属性。以前有人做过这样的事吗?

const Component = (props) => {
    const thisComponent = useRef(null);
    const otherFunction = ({ current, previousSibling  }) => {
        if (previousSibling) return previousSibling.focus();
        if (!previousSibling && current) return current.focus();
    } 
    const handleFocus = () => {
        const {current} = thisComponent;
        otherFunction(current);
    }
     return (
        <div ref={thisComponent} onFocus={handleFocus}>Stuff In here</div>
    );
};

1 个答案:

答案 0 :(得分:2)

这是我针对您案件的测试策略。我使用jest.spyOn方法来监视React.useRef钩子。它将让我们模拟SFC的ref对象的不同返回值。

index.tsx

import React, { RefObject } from 'react';
import { useRef } from 'react';

export const Component = props => {
  const thisComponent: RefObject<HTMLDivElement> = useRef(null);
  const otherFunction = ({ current, previousSibling }) => {
    if (previousSibling) return previousSibling.focus();
    if (!previousSibling && current) return current.focus();
  };
  const handleFocus = () => {
    const { current } = thisComponent;
    const previousSibling = current ? current.previousSibling : null;
    otherFunction({ current, previousSibling });
  };
  return (
    <div ref={thisComponent} onFocus={handleFocus}>
      Stuff In here
    </div>
  );
};

index.spec.tsx

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

describe('Component', () => {
  const focus = jest.fn();
  beforeEach(() => {
    jest.restoreAllMocks();
    jest.resetAllMocks();
  });
  test('should render correctly', () => {
    const wrapper = shallow(<Component></Component>);
    const div = wrapper.find('div');
    expect(div.text()).toBe('Stuff In here');
  });
  test('should handle click event correctly when previousSibling does not exist', () => {
    const useRefSpy = jest.spyOn(React, 'useRef').mockReturnValueOnce({ current: { focus } });
    const wrapper = shallow(<Component></Component>);
    wrapper.find('div').simulate('focus');
    expect(useRefSpy).toBeCalledTimes(1);
    expect(focus).toBeCalledTimes(1);
  });

  test('should render and handle click event correctly when previousSibling exists', () => {
    const useRefSpy = jest.spyOn(React, 'useRef').mockReturnValueOnce({ current: { previousSibling: { focus } } });
    const wrapper = shallow(<Component></Component>);
    wrapper.find('div').simulate('focus');
    expect(useRefSpy).toBeCalledTimes(1);
    expect(focus).toBeCalledTimes(1);
  });

  test('should render and handle click event correctly when current does not exist', () => {
    const useRefSpy = jest.spyOn(React, 'useRef').mockReturnValueOnce({ current: null });
    const wrapper = shallow(<Component></Component>);
    wrapper.find('div').simulate('focus');
    expect(useRefSpy).toBeCalledTimes(1);
    expect(focus).not.toBeCalled();
  });
});

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

 PASS  src/stackoverflow/56739670/index.spec.tsx (6.528s)
  Component
    ✓ should render correctly (10ms)
    ✓ should handle click event correctly when previousSibling does not exist (3ms)
    ✓ should render and handle click event correctly when previousSibling exists (1ms)
    ✓ should render and handle click event correctly when current does not exist (2ms)

-----------|----------|----------|----------|----------|-------------------|
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:       4 passed, 4 total
Snapshots:   0 total
Time:        7.689s

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