You need to enable JavaScript to run this app. React 18如何实现浅层渲染?Item组件测试遇阻求助
优惠活动
大模型
产品
解决方案
定价
更多

React 18如何实现浅层渲染?Item组件测试遇阻求助

React Item组件测试解决方案

1. 报错原因与修复

你遇到的Cannot destructure property 'basename' of 'React__namespace.useContext(...)' as it is null错误,是因为Item里的Link组件依赖react-router-dom的路由上下文,直接渲染组件时没有提供该上下文导致的。

2. 是否需要浅层渲染?

不需要。现代React测试推荐遵循用户视角,用@testing-library/react的完整渲染(配合必要的上下文提供者),而非浅层渲染。浅层渲染多用于测试组件内部实现细节,不符合当前主流测试理念。

3. 代码修正与测试实现

先修正Item组件的props解构错误

你的组件参数写成了({info},{addCart}),但React组件的props是单一对象,这样会导致addCart无法被正确获取,修正后代码:

import { Link } from "react-router-dom";
import React from "react";

const Item = ({ info, addCart }) => {
  return (
    <>
      <button data-testid='link'>
        <Link to="/">X</Link>
      </button>
      <img data-testid='pic' src={info.pic} alt={info.title} />
      <h1 data-testid='title'>{info.title}</h1>
      <p data-testid='description'>{info.description}</p>
      <button data-testid='add-item' onClick={() => addCart({ info })}>Add</button>
    </>
  );
};

export default Item;

完整测试代码(item.test.js)

用MemoryRouter提供路由上下文,同时覆盖元素渲染验证、按钮功能测试:

import React from "react";
import { render, cleanup, screen, fireEvent } from "@testing-library/react";
import '@testing-library/jest-dom';
import { MemoryRouter } from "react-router-dom";
import Item from "./item";

afterEach(cleanup);
const details = { pic: `a pic`, title: `a title`, description: `a description` };
const mockAddCart = jest.fn(); 

// 封装带路由的渲染工具函数
const renderWithRouter = (ui) => {
  return render(ui, { wrapper: MemoryRouter });
};

test('所有组件元素正常渲染', () => {
  renderWithRouter(<Item info={details} addCart={mockAddCart} />);
  
  // 验证返回按钮存在
  expect(screen.getByTestId('link')).toBeInTheDocument();
  // 验证图片属性正确
  expect(screen.getByTestId('pic')).toHaveAttribute('src', details.pic);
  expect(screen.getByTestId('pic')).toHaveAttribute('alt', details.title);
  // 验证标题、描述内容正确
  expect(screen.getByTestId('title')).toHaveTextContent(details.title);
  expect(screen.getByTestId('description')).toHaveTextContent(details.description);
  // 验证Add按钮存在
  expect(screen.getByTestId('add-item')).toBeInTheDocument();
});

test('点击Add按钮触发指定函数', () => {
  renderWithRouter(<Item info={details} addCart={mockAddCart} />);
  
  // 模拟用户点击按钮
  fireEvent.click(screen.getByTestId('add-item'));
  
  // 验证函数调用次数与参数
  expect(mockAddCart).toHaveBeenCalledTimes(1);
  expect(mockAddCart).toHaveBeenCalledWith({ info: details });
});

4. 最新文档参考

  • @testing-library/react官方文档
  • react-router-dom官方测试指南
  • Jest官方文档(模拟函数章节)

内容的提问来源于stack exchange,提问作者wavesinaroom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 16:47:51