在测试使用 react-spring 和 @testing-library/react 动画的组件时,由于对 ForwardRef 的更新而引发警告

A warning is thrown because of an update to ForwardRef when testing a component animated with react-spring with @testing-library/react

我有一个使用 useSpring 挂钩的 react-spring 动画组件。类似于:

function Toggle({ handleToggle, toggled }) {
  const x = useSpring({
    x: toggled ? 1 : 0
  });
  return (
    <div className={styles.switch} onToggle={handleToggle} data-testid="switch">
      <animated.div
        className={styles.circle}
        style={{
          transform: x
            .interpolate({
              range: [0, 0.4, 0.8, 1],
              output: [0, 5, 10, 16]
            })
            .interpolate((x) => `translateX(${x}px)`)
        }}>
        &nbsp;
      </animated.div>
    </div>
  );
}

测试组件时抛出警告:

Warning: An update to ForwardRef inside a test was not wrapped in act(...).

      When testing, code that causes React state updates should be wrapped into act(...):

      act(() => {
        /* fire events that update state */
      });
      /* assert on the output */

      This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/docs/test-utils.html#act
          in ForwardRef (created by Toggle)
          in Toggle

我的测试代码是:

test("Toggle works", () => {
    let toggled = false;
    const handleToggle = jest.fn(() => {
      toggled = true;
    });
    const { getByTestId, queryByTestId } = render(
      <Toggle toggled={toggled} handleToggle={handleToggle}/>
    );
  });

我应该如何使用 @testing-library/react 测试使用 react-spring 动画的组件?

我在测试在 react-test-renderer 渲染器快照创建中使用 useSpring<animated.div> 的组件时收到此警告:

import renderer from 'react-test-renderer';
//(...)
  it('matches snapshot', () => {
    const tree = renderer.create(<Component />).toJSON();
    expect(tree).toMatchSnapshot();
  });
//(...)

我找到了灵感 in this link,只需添加 Jest 的 useFakeTimers 调用即可解决:

import renderer from 'react-test-renderer';
//(...)
  it('matches snapshot', () => {
    jest.useFakeTimers(); //ADDED
    const tree = renderer.create(<Component />).toJSON();
    expect(tree).toMatchSnapshot();
  });
//(...)

看到用 act 包装的东西,就像在引用的 link 中一样,在这种情况下是没有必要的。

在研究过程中我还发现了以下博客 post,它解释了原因并描述了显示此警告的一些情况,包括您使用 jest.useFakeTimers() 时的情况,警告一直存在显示并使用 act 是必要的:Fix the "not wrapped in act(...)" warning