测试已记忆的组件是否未重新渲染

问题描述 投票:0回答:1

在我的上一次提交中,我降低了 React 应用程序的性能(我引入了 Context,并且我了解到它会干扰 Memoization)。

我想添加测试来检查记忆组件在用户操作后是否不会重新渲染。

App.jsx

import {MemoizedChildComponent} from "./ChildComponent"

export function App() {
 return (
  <div>
   ...
   <MemoizedChildComponent prop1={...} prop2../>
   ...
  </div>
 )
}

ChildComponent.jsx

import {memo} from "react"

function ChildComponent({prop1, prop2,...}) {
 return (
   ...
 )
}

const MemoizedChildComponent = memo(ChildComponent);

export { MemoizedChildComponent};

使用 Jest 和 React 测试库,我想编写这个测试:

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { App } from "./App"

test("ChildComponent was not rerendered", async () => {
  render(<App>);
  await userEvent.click(...)

  // Assert that ChildComponent was not rerendered
}

我在React测试库API中进行了搜索,但找不到监听渲染事件的方法。我想过 Jest 模拟,但我不想替换 ChildComponent,而是监听它的渲染事件。

您有编写此测试的建议吗?

reactjs jestjs react-testing-library memoization
1个回答
0
投票

我终于能够让它发挥作用了。这个SO答案提供了我访问记忆化组件的底层组件所需的信息。

所以我的解决方案

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { App } from "./App"
import * as ChildComponentModule from "../../RecordRow/RecordRow";


jest.mock("./ChildComponent", () => {
  const ChildComponentModule = jest.requireActual("./ChildComponent");
  return {
    ...ChildComponentModule, // Unnecessary if there's only 1 exported item
    MemoizedChildComponent : {
      ...ChildComponentModule.MemoizedChildComponent,
      type: jest.spyOn(ChildComponentModule.MemoizedChildComponent, "type"), // Spy on the underlying ChildComponent of MemoizedChildComponent
    },
  };
});

test("ChildComponent was not rerendered", async () => {
  render(<App>);
  jest.clearAllMocks(); // ignore initial renders
  await userEvent.click(...)

  // Assert that ChildComponent was not rerendered
expect(ChildComponentModule.MemoizedChildComponent.type).not.toHaveBeenCalled();

}

就我而言,我使用命名导出。对于默认导出,您可以使用此语法

© www.soinside.com 2019 - 2024. All rights reserved.