You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React与D3v4集成:表格饼图应用及Jest测试问题咨询

React + D3v4 + Jest: Data Sync, Data Transformation & Testing Validation

What I'm Working On

I'm building a basic integration example combining React, D3v4, and Jest testing. So far, I've implemented a table component and a pie chart component with these core requirements:

  • Sync app-level data to both the table and pie chart components
  • The pie chart should only populate data after a user clicks a row in the table

I've got the basic component rendering working, but I'm stuck on two key issues and need some guidance.

My Issues

  1. Data Transformation Problem: The props passed to my pie chart need to be restructured into a label-value format from the raw data I have. I'm having trouble getting this parsing/transformation right.
  2. Test Validation: I wrote some Jest tests for the components, but I'm not sure if they follow best practices or if the logic is correct. I need someone to review them.

Raw Data Format Example

Here's what my source data looks like:

[
  {
    "Country": "Afghanistan",
    "TotalConfirmed": 20917,
    "TotalDeaths": 369,
    "TotalRecovered": 2171
  },
  {
    "Country": "Albania",
    "TotalConfirmed": 1263,
    "TotalDeaths": 34,
    "TotalRecovered": 945
  },
  {
    "Country": "Algeria",
    "TotalConfirmed": 10265,
    "TotalDeaths": 715,
    "TotalRecovered": 6799
  }
]

Code Snippets for Review

Core Component Code

Table Component

import React from 'react';

const TableComponent = ({ data, onRowClick }) => {
  return (
    <table>
      <thead>
        <tr>
          <th>Country</th>
          <th>Total Confirmed</th>
          <th>Total Deaths</th>
          <th>Total Recovered</th>
        </tr>
      </thead>
      <tbody>
        {data.map((country, idx) => (
          <tr key={idx} onClick={() => onRowClick(country)}>
            <td>{country.Country}</td>
            <td>{country.TotalConfirmed}</td>
            <td>{country.TotalDeaths}</td>
            <td>{country.TotalRecovered}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
};

export default TableComponent;

Pie Chart Component (where data transformation happens)

import React, { useEffect, useRef } from 'react';
import * as d3 from 'd3';

const PieChart = ({ selectedCountryData }) => {
  const svgRef = useRef(null);

  useEffect(() => {
    if (!selectedCountryData) return;

    // This is where I'm trying to transform data to label-value format
    const pieData = Object.entries(selectedCountryData)
      .filter(([key]) => key !== 'Country')
      .map(([label, value]) => ({ label, value }));

    // D3 pie chart rendering logic
    const svg = d3.select(svgRef.current);
    svg.selectAll('*').remove();

    const dimensions = { width: 400, height: 400 };
    const radius = Math.min(dimensions.width, dimensions.height) / 2;

    const pieGenerator = d3.pie().value(d => d.value);
    const arcGenerator = d3.arc().innerRadius(0).outerRadius(radius);

    const group = svg.append('g')
      .attr('transform', `translate(${dimensions.width/2}, ${dimensions.height/2})`);

    group.selectAll('path')
      .data(pieGenerator(pieData))
      .enter()
      .append('path')
      .attr('d', arcGenerator)
      .attr('fill', (_, i) => d3.schemeCategory10[i]);
  }, [selectedCountryData]);

  return <svg ref={svgRef} width={400} height={400} aria-label="Pie chart of country stats" />;
};

export default PieChart;

Jest Test Code (Pie Chart)

import React from 'react';
import { render, screen } from '@testing-library/react';
import PieChart from './PieChart';

describe('PieChart Component', () => {
  test('renders no slices when no data is passed', () => {
    render(<PieChart selectedCountryData={null} />);
    const svg = screen.getByRole('img', { name: /pie chart of country stats/i });
    expect(svg.children).toHaveLength(0);
  });

  test('renders 3 slices when valid country data is passed', () => {
    const testData = {
      Country: 'Testland',
      TotalConfirmed: 500,
      TotalDeaths: 25,
      TotalRecovered: 300
    };
    render(<PieChart selectedCountryData={testData} />);
    const pieSlices = screen.getAllByRole('path');
    expect(pieSlices).toHaveLength(3);
  });
});

Specific Questions

  1. Is my current data transformation logic (turning the country object into label-value pairs) correct? Are there edge cases I'm missing, or a cleaner way to do this with React/D3?
  2. Do my Jest tests follow best practices? Are there any gaps in the test coverage, or changes I should make to ensure the tests are reliable?

内容的提问来源于stack exchange,提问作者The Old County

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 21:32:47