Skip to content

Put back Area event handlers#6507

Merged
ckifer merged 2 commits intomainfrom
area-onclick
Oct 25, 2025
Merged

Put back Area event handlers#6507
ckifer merged 2 commits intomainfrom
area-onclick

Conversation

@PavelVanecek
Copy link
Collaborator

@PavelVanecek PavelVanecek commented Oct 25, 2025

Description

I made a mistake when refactoring.

Related Issue

Fixes #6493

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

Checklist:

  • My change requires a change to the documentation.
  • I have updated the documentation accordingly.
  • I have added tests to cover my changes.
  • I have added a storybook story or VR test, or extended an existing story or VR test to show my changes

Summary by CodeRabbit

  • Tests

    • Comprehensive event interaction tests added across all chart types (Area, Bar, Line, Scatter, Sankey, Sunburst, Treemap, Pie, Radar, RadialBar)
    • Tests validate click, hover, and touch event handling
    • Event payload structures verified for accuracy
  • Bug Fixes

    • Improved SVG event property handling during chart rendering

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 25, 2025

Walkthrough

This PR adds event handling to the Area component via SVG event properties and introduces comprehensive event-related tests across multiple chart types (Bar, Line, Scatter, Sankey, SunburstChart, Treemap, Pie, Radar, RadialBar) to validate click, hover, and touch interactions with expected payloads.

Changes

Cohort / File(s) Summary
Production: Area Event Handling
src/cartesian/Area.tsx
Imports svgPropertiesAndEvents helper and computes propsWithEvents from remaining props, spreading event-related SVG properties into the Curve component.
Test: Cartesian Charts
test/cartesian/Area.spec.tsx, test/cartesian/Bar.spec.tsx, test/cartesian/Line.spec.tsx, test/cartesian/Scatter.spec.tsx
Adds comprehensive event-handling tests (onClick, onMouseOver/onMouseOut, onTouchMove/onTouchEnd) with payload assertions; introduces userEventSetup helper and event simulation utilities.
Test: Chart Components
test/chart/Sankey.spec.tsx, test/chart/SunburstChart.spec.tsx, test/chart/Treemap.spec.tsx
Adds event-focused test suites for links and nodes (where applicable) verifying click, hover, and touch interactions; uses expectLastCalledWith and mockTouchingElement helpers.
Test: Polar Charts
test/polar/Pie.spec.tsx, test/polar/Radar.spec.tsx, test/polar/RadialBar.spec.tsx
Adds event-handling tests for sectors and polygons with detailed payload validation for mouse and touch events; introduces new test helpers (fireEvent, userEventSetup, assertNotNull, expectLastCalledWith).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Production logic: Single file (Area.tsx) with straightforward event property delegation to Curve component.
  • Test homogeneity: Similar event test patterns repeated across 10 test files (click, hover, touch) reduce cognitive overhead per file but require verification of consistency.
  • Breadth: Changes span multiple chart types and interaction paths; verify payload structures align across chart types.
  • Attention areas:
    • Event payload structures and consistency across chart components
    • Test helper usage (userEventSetup, mockTouchingElement, expectLastCalledWith) applied consistently
    • Duplicate test suites noted in some files (e.g., Pie.spec.tsx, Radar.spec.tsx) — verify intentionality

Suggested reviewers

  • ckifer

Poem

🐰✨ Events now flow through charts so bright,
From clicks and hovers, touches light,
A rabbit's hop through interactions spry,
Tests ensure no payload passes by! 🎯

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The pull request description is largely incomplete compared to the required template. While it includes a Related Issue link and properly identifies the change type as a bug fix, it severely lacks critical sections. The Description section contains only "I made a mistake when refactoring," which is vague and provides no detail about what was changed. The Motivation and Context section is entirely missing—there is no explanation of what problem this solves or why the change was required. The How Has This Been Tested section is also completely absent, providing no details about testing approach or validation. The description fails to adequately communicate the nature and impact of the changes to reviewers.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The title "Put back Area event handlers" clearly and specifically identifies the main change in the pull request. According to the PR objectives and raw summary, the author made a mistake during refactoring and is restoring Area event handlers to the Curve component. The title directly captures this restoration intent and is concise, descriptive, and easy to understand without unnecessary noise. A reviewer scanning commit history would immediately understand the primary purpose of this change.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch area-onclick

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/cartesian/Area.tsx (1)

323-337: Area events break when fill is transparent or 'none'

You attach handlers only to the fill path (stroke is explicitly none). If users set fill="none" or fillOpacity={0}, pointer events won’t hit the area, and the stroke path has no handlers — interactions are lost.

Option A (minimal): force pointer events on the area path when it’s not visually painted.

   const allOtherProps = svgPropertiesNoEvents(propsWithoutId);
   const propsWithEvents = svgPropertiesAndEvents(propsWithoutId);
+  const isFillInteractable = props.fill !== 'none' && (props.fillOpacity ?? 1) > 0;

   return (
     <>
       {points?.length > 1 && (
         <Layer clipPath={needClip ? `url(#clipPath-${clipPathId})` : undefined}>
           <Curve
-            {...propsWithEvents}
+            {...propsWithEvents}
+            pointerEvents={isFillInteractable ? undefined : 'all'}
             id={id}
             points={points}
             connectNulls={connectNulls}
             type={type}
             baseLine={baseLine}
             layout={layout}
             stroke="none"
             className="recharts-area-area"
           />

Option B (broader): when the fill isn’t interactable, also pass handlers to the stroke curve (and/or set pointerEvents="stroke" there) to ensure line‑only areas remain clickable. I can draft this if you prefer.

test/polar/Pie.spec.tsx (1)

2091-2097: Avoid any in TypeScript tests.

Replace any with concrete types to satisfy "never use any" guideline. The suggested type { name: string; value: number } correctly matches the data structure being passed to both callbacks.

Apply the following changes at lines 2091-2097 and 2130-2136:

-      const outerRadiusCallback = (dataPoint: any) => {
+      const outerRadiusCallback = (dataPoint: { name: string; value: number }) => {
🧹 Nitpick comments (18)
test/chart/Treemap.spec.tsx (2)

11-11: Unnecessary import in this test.

The mockTouchingElement helper is imported but not meaningfully used in the new test. The test directly fires touchMove on a DOM element without relying on document.elementFromPoint, which is what mockTouchingElement sets up.


741-764: Complete the test coverage for both touch event handlers.

The test defines both onTouchMove and onTouchEnd mocks but only verifies that onTouchMove is not called. For completeness, the test should also verify that onTouchEnd is not called.

Additionally, the mockTouchingElement call on line 742 is not needed since the test directly fires events on DOM elements without using document.elementFromPoint.

Apply this diff to improve test coverage and remove unnecessary setup:

   it('should not call touch event handlers', () => {
-    mockTouchingElement('0', 'size');
     const onTouchMove = vi.fn();
     const onTouchEnd = vi.fn();
     const { container } = render(
       <Treemap
         width={500}
         height={250}
         data={data}
         nameKey="name"
         dataKey="size"
         // @ts-expect-error typescript is correct here - indeed Treemap does not fire touch events. It shows Tooltip internally but doesn't allow external handlers
         onTouchMove={onTouchMove}
         onTouchEnd={onTouchEnd}
         isAnimationActive={false}
       />,
     );
 
     const firstNode = container.querySelectorAll('.recharts-treemap-depth-1 g')[0];
     expect(firstNode).toBeInTheDocument();
 
     fireEvent.touchMove(firstNode, { touches: [{ clientX: 200, clientY: 200 }] });
     expect(onTouchMove).toHaveBeenCalledTimes(0);
+    
+    fireEvent.touchEnd(firstNode);
+    expect(onTouchEnd).toHaveBeenCalledTimes(0);
   });
test/polar/RadialBar.spec.tsx (1)

1214-1267: Test the onTouchEnd handler for complete coverage.

The test sets up onTouchEnd (line 1216) and passes it to the component (line 1226), but never invokes or asserts it. For consistency with the mouse event test approach and to achieve complete coverage, add a fireEvent.touchEnd call and validation.

Add after line 1266:

+
+    fireEvent.touchEnd(sector, { touches: [{ clientX: 200, clientY: 200 }] });
+    expect(onTouchEnd).toHaveBeenCalledTimes(1);
+    expectLastCalledWith(
+      onTouchEnd,
+      {
+        name: 'Page A',
+        uv: 400,
+        pv: 2400,
+        amt: 2400,
+        background: {
+          cx: 250,
+          cy: 250,
+          innerRadius: 3.266666666666666,
+          outerRadius: 29.266666666666666,
+          startAngle: 0,
+          endAngle: 360,
+        },
+        payload: {
+          name: 'Page A',
+          uv: 400,
+          pv: 2400,
+          amt: 2400,
+        },
+        value: 2400,
+        cx: 250,
+        cy: 250,
+        innerRadius: 3.266666666666666,
+        outerRadius: 29.266666666666666,
+        startAngle: 0,
+        endAngle: 360,
+      },
+      0,
+      expect.any(Object),
+    );
test/polar/Radar.spec.tsx (1)

139-260: Consider extracting large test fixture to test/_data.ts.

The points array is ~120 lines of inline test data. Extracting it to test/_data.ts (alongside exampleRadarData) would improve readability and enable reuse if other tests need this fixture.

test/chart/SunburstChart.spec.tsx (2)

49-99: Consider extracting the duplicate payload structure to improve maintainability.

The same payload object (with name, fill, value, children, tooltipIndex) is repeated three times in this test. Extracting it to a constant would reduce duplication and make the test easier to maintain if the data structure changes.

Example refactor:

+  const expectedChild1Payload = {
+    name: 'Child1',
+    fill: '#264653',
+    value: 30,
+    children: [
+      {
+        name: 'third child',
+        value: 10,
+      },
+    ],
+    tooltipIndex: '[0]',
+  };
+
   await user.hover(sector);
   expect(onMouseEnter).toHaveBeenCalled();
   expectLastCalledWith(
     onMouseEnter,
-    {
-      name: 'Child1',
-      fill: '#264653',
-      value: 30,
-      children: [
-        {
-          name: 'third child',
-          value: 10,
-        },
-      ],
-      tooltipIndex: '[0]',
-    },
+    expectedChild1Payload,
     expect.any(Object),
   );

   await user.unhover(sector);
   expect(onMouseLeave).toHaveBeenCalled();
   expectLastCalledWith(
     onMouseLeave,
-    {
-      name: 'Child1',
-      fill: '#264653',
-      value: 30,
-      children: [
-        {
-          name: 'third child',
-          value: 10,
-        },
-      ],
-      tooltipIndex: '[0]',
-    },
+    expectedChild1Payload,
     expect.any(Object),
   );

   await user.click(sector);
   expect(onClick).toHaveBeenCalled();
   // click doesn't add the original event, not sure why?
-  expectLastCalledWith(onClick, {
-    name: 'Child1',
-    fill: '#264653',
-    value: 30,
-    children: [
-      {
-        name: 'third child',
-        value: 10,
-      },
-    ],
-    tooltipIndex: '[0]',
-  });
+  expectLastCalledWith(onClick, expectedChild1Payload);

102-120: Consider testing onTouchEnd or removing the unused setup.

The test sets up onTouchEnd at line 104 and passes it to the component at line 112, but never fires a touch end event or verifies it wasn't called. Since the test validates that touch event callbacks are not fired, either add a fireEvent.touchEnd assertion or remove the unused onTouchEnd setup to avoid confusion.

Option 1 - Test both callbacks:

   fireEvent.touchMove(sector, { touches: [{ clientX: 200, clientY: 200 }] });
   expect(onTouchMove).not.toHaveBeenCalled();
+  
+  fireEvent.touchEnd(sector);
+  expect(onTouchEnd).not.toHaveBeenCalled();

Option 2 - Remove unused setup:

   it('does not call touch event callbacks', async () => {
     const onTouchMove = vi.fn();
-    const onTouchEnd = vi.fn();

     const { container } = rechartsTestRender(
       <SunburstChart
         width={500}
         height={500}
         // @ts-expect-error typescript is correct here - indeed SunburstChart does not fire touch events
         onTouchMove={onTouchMove}
-        onTouchEnd={onTouchEnd}
         data={exampleSunburstData}
       />,
     );
src/cartesian/Area.tsx (1)

319-323: Don’t forward animation callbacks as DOM event handlers

svgPropertiesAndEvents(propsWithoutId) will include onAnimationStart/onAnimationEnd from internal props, unintentionally wiring them as DOM animation events. Strip them before collecting SVG+event props.

-  const { id, ...propsWithoutId } = props;
-  const allOtherProps = svgPropertiesNoEvents(propsWithoutId);
-  const propsWithEvents = svgPropertiesAndEvents(propsWithoutId);
+  const { id, onAnimationStart, onAnimationEnd, ...propsWithoutId } = props;
+  const allOtherProps = svgPropertiesNoEvents(propsWithoutId);
+  const propsWithEvents = svgPropertiesAndEvents(propsWithoutId);
test/cartesian/Bar.spec.tsx (1)

1720-1918: Solid event coverage; consider reducing brittleness of payload assertions.

Deep-equality on many numeric fields (e.g., tooltipPosition/background) can be flaky with minor layout tweaks. Prefer expect.objectContaining for stable keys and types; assert only what matters (index, dataKey/value, coordinates exist).

test/cartesian/Scatter.spec.tsx (3)

265-329: Disable animation in interaction tests to reduce flakiness.

Set isAnimationActive={false} on Scatter for deterministic geometry during clicks.

-        <ScatterChart width={500} height={500}>
-          <Scatter data={data} dataKey="cx" onClick={handleClick} />
+        <ScatterChart width={500} height={500}>
+          <Scatter isAnimationActive={false} data={data} dataKey="cx" onClick={handleClick} />

330-447: Same: hover tests should also disable animation.

-        <ScatterChart width={500} height={500}>
-          <Scatter data={data} dataKey="cx" onMouseOver={handleMouseOver} onMouseOut={handleMouseOut} />
+        <ScatterChart width={500} height={500}>
+          <Scatter
+            isAnimationActive={false}
+            data={data}
+            dataKey="cx"
+            onMouseOver={handleMouseOver}
+            onMouseOut={handleMouseOut}
+          />

448-567: Same: touch tests should also disable animation.

-        <ScatterChart width={500} height={500}>
-          <Scatter data={data} dataKey="cx" onTouchMove={handleTouchMove} onTouchEnd={handleTouchEnd} />
+        <ScatterChart width={500} height={500}>
+          <Scatter
+            isAnimationActive={false}
+            data={data}
+            dataKey="cx"
+            onTouchMove={handleTouchMove}
+            onTouchEnd={handleTouchEnd}
+          />
test/cartesian/Area.spec.tsx (4)

223-255: Turn off animation in Area click test for stability.

-          <Area dataKey="value" onClick={handleClick} />
+          <Area isAnimationActive={false} dataKey="value" onClick={handleClick} />

263-296: Turn off animation in Area hover test for stability.

-          <Area dataKey="value" onMouseOver={handleMouseOver} onMouseOut={handleMouseOut} />
+          <Area
+            isAnimationActive={false}
+            dataKey="value"
+            onMouseOver={handleMouseOver}
+            onMouseOut={handleMouseOut}
+          />

318-353: Turn off animation in Area touch test for stability.

-          <Area dataKey="value" onTouchMove={handleTouchMove} onTouchEnd={handleTouchEnd} />
+          <Area
+            isAnimationActive={false}
+            dataKey="value"
+            onTouchMove={handleTouchMove}
+            onTouchEnd={handleTouchEnd}
+          />

189-353: Reduce assertion fragility in event payloads.

Use expect.objectContaining for stable keys (id layout points length etc.) instead of full deep objects with many numeric fields.

test/chart/Sankey.spec.tsx (1)

450-806: Prefer partial assertions to avoid over-specifying sankey geometry.

These deep payload matches (dy/x/y/control points, nested node/link structures) are brittle to layout tweaks. Assert structure with expect.objectContaining and numeric existence (expect.any(Number)) for coordinates/widths, plus index/type ('link'|'node').

test/cartesian/Line.spec.tsx (1)

269-447: LGTM; consider partial payload assertions.

Great coverage for click/hover/touch. To reduce brittleness, assert only stable properties using expect.objectContaining (e.g., className/id/points length/stroke), not every numeric field.

test/polar/Pie.spec.tsx (1)

1804-2081: Event tests look good; consider partial assertions.

Coverage is solid. For resilience, assert with expect.objectContaining for stable fields (name, value, percent, tooltipPayload shape) instead of full deep equality on all numerics.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 08090fd and 5318073.

📒 Files selected for processing (11)
  • src/cartesian/Area.tsx (2 hunks)
  • test/cartesian/Area.spec.tsx (3 hunks)
  • test/cartesian/Bar.spec.tsx (3 hunks)
  • test/cartesian/Line.spec.tsx (3 hunks)
  • test/cartesian/Scatter.spec.tsx (2 hunks)
  • test/chart/Sankey.spec.tsx (2 hunks)
  • test/chart/SunburstChart.spec.tsx (2 hunks)
  • test/chart/Treemap.spec.tsx (2 hunks)
  • test/polar/Pie.spec.tsx (2 hunks)
  • test/polar/Radar.spec.tsx (3 hunks)
  • test/polar/RadialBar.spec.tsx (2 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
{test,www/test}/**

📄 CodeRabbit inference engine (DEVELOPING.md)

Place unit tests in the test directory; some tests may also live in www/test

Files:

  • test/chart/SunburstChart.spec.tsx
  • test/chart/Treemap.spec.tsx
  • test/polar/RadialBar.spec.tsx
  • test/chart/Sankey.spec.tsx
  • test/cartesian/Bar.spec.tsx
  • test/polar/Pie.spec.tsx
  • test/cartesian/Area.spec.tsx
  • test/polar/Radar.spec.tsx
  • test/cartesian/Scatter.spec.tsx
  • test/cartesian/Line.spec.tsx
test/**/*.spec.{ts,tsx}

📄 CodeRabbit inference engine (CONTRIBUTING.md)

test/**/*.spec.{ts,tsx}: When writing new code, aim for 100% unit test code coverage
When adding or changing functionality, add appropriate tests (prefer unit tests; use RTL if rendering is involved)

Files:

  • test/chart/SunburstChart.spec.tsx
  • test/chart/Treemap.spec.tsx
  • test/polar/RadialBar.spec.tsx
  • test/chart/Sankey.spec.tsx
  • test/cartesian/Bar.spec.tsx
  • test/polar/Pie.spec.tsx
  • test/cartesian/Area.spec.tsx
  • test/polar/Radar.spec.tsx
  • test/cartesian/Scatter.spec.tsx
  • test/cartesian/Line.spec.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CONTRIBUTING.md)

**/*.{ts,tsx}: Ensure code lints cleanly before submitting PRs (npm run lint)
Never use the TypeScript any type (implicit or explicit)
Prefer unknown over any and refine types appropriately
Explicitly type all function parameters and return values; do not rely on implicit any or inference
Do not use as type assertions; the only exception is as const

Files:

  • test/chart/SunburstChart.spec.tsx
  • test/chart/Treemap.spec.tsx
  • test/polar/RadialBar.spec.tsx
  • test/chart/Sankey.spec.tsx
  • test/cartesian/Bar.spec.tsx
  • test/polar/Pie.spec.tsx
  • test/cartesian/Area.spec.tsx
  • test/polar/Radar.spec.tsx
  • test/cartesian/Scatter.spec.tsx
  • src/cartesian/Area.tsx
  • test/cartesian/Line.spec.tsx
src/**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Do not hardcode any user-facing strings or formatting choices in the library code; leave internationalization to library users

Files:

  • src/cartesian/Area.tsx
🧠 Learnings (9)
📚 Learning: 2025-10-25T07:35:46.180Z
Learnt from: CR
PR: recharts/recharts#0
File: test/README.md:0-0
Timestamp: 2025-10-25T07:35:46.180Z
Learning: Applies to test/**/*.test.{ts,tsx} : Use expectLastCalledWith instead of toHaveBeenLastCalledWith for typed last-call assertions

Applied to files:

  • test/chart/SunburstChart.spec.tsx
📚 Learning: 2025-10-25T07:35:46.180Z
Learnt from: CR
PR: recharts/recharts#0
File: test/README.md:0-0
Timestamp: 2025-10-25T07:35:46.180Z
Learning: Applies to test/**/*.test.{ts,tsx} : Mock getBoundingClientRect using test/helper/MockGetBoundingClientRect.ts when rendering Recharts components (e.g., Tooltip, Legend, charts)

Applied to files:

  • test/chart/Treemap.spec.tsx
  • test/chart/Sankey.spec.tsx
  • test/cartesian/Bar.spec.tsx
  • test/cartesian/Scatter.spec.tsx
📚 Learning: 2025-10-25T07:35:14.559Z
Learnt from: CR
PR: recharts/recharts#0
File: CONTRIBUTING.md:0-0
Timestamp: 2025-10-25T07:35:14.559Z
Learning: Applies to test/component/**/*.spec.tsx : Test rendering behavior and component interactions with React Testing Library

Applied to files:

  • test/chart/Treemap.spec.tsx
  • test/polar/RadialBar.spec.tsx
  • test/cartesian/Bar.spec.tsx
  • test/polar/Pie.spec.tsx
  • test/cartesian/Area.spec.tsx
  • test/polar/Radar.spec.tsx
  • test/cartesian/Line.spec.tsx
📚 Learning: 2025-10-25T07:35:46.180Z
Learnt from: CR
PR: recharts/recharts#0
File: test/README.md:0-0
Timestamp: 2025-10-25T07:35:46.180Z
Learning: Write unit tests using Vitest and React Testing Library

Applied to files:

  • test/polar/RadialBar.spec.tsx
  • test/cartesian/Bar.spec.tsx
  • test/polar/Pie.spec.tsx
  • test/cartesian/Area.spec.tsx
  • test/polar/Radar.spec.tsx
  • test/cartesian/Line.spec.tsx
📚 Learning: 2025-10-25T07:35:46.180Z
Learnt from: CR
PR: recharts/recharts#0
File: test/README.md:0-0
Timestamp: 2025-10-25T07:35:46.180Z
Learning: Applies to test/**/*.test.{ts,tsx} : In tests not using createSelectorTestCase, advance timers after renders with vi.runOnlyPendingTimers()

Applied to files:

  • test/polar/RadialBar.spec.tsx
📚 Learning: 2025-10-25T07:35:46.180Z
Learnt from: CR
PR: recharts/recharts#0
File: test/README.md:0-0
Timestamp: 2025-10-25T07:35:46.180Z
Learning: Applies to test/**/*.test.{ts,tsx} : When using user-event, initialize with userEvent.setup({ advanceTimers: vi.runOnlyPendingTimers }) or use test/helper/userEventSetup.ts

Applied to files:

  • test/cartesian/Bar.spec.tsx
  • test/cartesian/Area.spec.tsx
📚 Learning: 2025-10-25T07:35:46.180Z
Learnt from: CR
PR: recharts/recharts#0
File: test/README.md:0-0
Timestamp: 2025-10-25T07:35:46.180Z
Learning: Applies to test/**/*.test.{ts,tsx} : Prefer using the createSelectorTestCase helper when writing or modifying tests

Applied to files:

  • test/cartesian/Area.spec.tsx
📚 Learning: 2025-10-25T07:35:46.180Z
Learnt from: CR
PR: recharts/recharts#0
File: test/README.md:0-0
Timestamp: 2025-10-25T07:35:46.180Z
Learning: Applies to test/**/*.test.{ts,tsx} : When testing selectors, verify render counts using the spy and rerenderSameComponent from createSelectorTestCase

Applied to files:

  • test/cartesian/Area.spec.tsx
  • test/cartesian/Line.spec.tsx
📚 Learning: 2025-10-25T07:35:14.559Z
Learnt from: CR
PR: recharts/recharts#0
File: CONTRIBUTING.md:0-0
Timestamp: 2025-10-25T07:35:14.559Z
Learning: Applies to test/**/*.spec.{ts,tsx} : When adding or changing functionality, add appropriate tests (prefer unit tests; use RTL if rendering is involved)

Applied to files:

  • test/polar/Radar.spec.tsx
🧬 Code graph analysis (11)
test/chart/SunburstChart.spec.tsx (2)
test/helper/expectLastCalledWith.ts (1)
  • expectLastCalledWith (14-34)
test/_data.ts (1)
  • exampleSunburstData (167-199)
test/chart/Treemap.spec.tsx (2)
test/helper/mockTouchingElement.ts (1)
  • mockTouchingElement (18-23)
src/chart/Treemap.tsx (2)
  • render (903-925)
  • Treemap (938-982)
test/polar/RadialBar.spec.tsx (3)
test/helper/expectLastCalledWith.ts (1)
  • expectLastCalledWith (14-34)
src/polar/RadialBar.tsx (2)
  • render (362-380)
  • RadialBar (551-576)
test/_data.ts (1)
  • PageData (4-11)
test/chart/Sankey.spec.tsx (6)
src/chart/Sankey.tsx (1)
  • Sankey (943-986)
test/_data.ts (1)
  • exampleSankeyData (13-134)
test/component/Tooltip/tooltipMouseHoverSelectors.ts (2)
  • sankeyLinkMouseHoverTooltipSelector (44-45)
  • sankeyNodeMouseHoverTooltipSelector (42-43)
test/helper/assertNotNull.ts (1)
  • assertNotNull (1-5)
test/helper/expectLastCalledWith.ts (1)
  • expectLastCalledWith (14-34)
test/helper/mockTouchingElement.ts (1)
  • mockTouchingElement (18-23)
test/cartesian/Bar.spec.tsx (4)
test/helper/userEventSetup.ts (1)
  • userEventSetup (13-17)
test/helper/renderWithStrictMode.ts (1)
  • renderWithStrictMode (4-9)
test/helper/expectBars.ts (1)
  • getAllBars (13-15)
test/helper/expectLastCalledWith.ts (1)
  • expectLastCalledWith (14-34)
test/polar/Pie.spec.tsx (3)
test/helper/userEventSetup.ts (1)
  • userEventSetup (13-17)
test/_data.ts (1)
  • PageData (4-11)
test/helper/expectLastCalledWith.ts (1)
  • expectLastCalledWith (14-34)
test/cartesian/Area.spec.tsx (3)
test/helper/userEventSetup.ts (1)
  • userEventSetup (13-17)
test/helper/assertNotNull.ts (1)
  • assertNotNull (1-5)
test/helper/expectLastCalledWith.ts (1)
  • expectLastCalledWith (14-34)
test/polar/Radar.spec.tsx (5)
test/helper/userEventSetup.ts (1)
  • userEventSetup (13-17)
test/_data.ts (1)
  • exampleRadarData (201-210)
src/polar/Radar.tsx (1)
  • Radar (546-568)
test/helper/assertNotNull.ts (1)
  • assertNotNull (1-5)
test/helper/expectLastCalledWith.ts (1)
  • expectLastCalledWith (14-34)
test/cartesian/Scatter.spec.tsx (2)
test/helper/userEventSetup.ts (1)
  • userEventSetup (13-17)
test/helper/mockTouchingElement.ts (1)
  • mockTouchingElement (18-23)
src/cartesian/Area.tsx (3)
src/util/svgPropertiesAndEvents.ts (1)
  • svgPropertiesAndEvents (19-24)
src/container/Layer.tsx (1)
  • Layer (13-22)
src/shape/Curve.tsx (1)
  • Curve (182-200)
test/cartesian/Line.spec.tsx (3)
test/helper/userEventSetup.ts (1)
  • userEventSetup (13-17)
test/helper/assertNotNull.ts (1)
  • assertNotNull (1-5)
test/helper/expectLastCalledWith.ts (1)
  • expectLastCalledWith (14-34)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Build, Test, Pack
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (5)
test/polar/RadialBar.spec.tsx (1)

1086-1212: Comprehensive event handler validation looks good.

The expanded assertions now verify exact call counts and complete payload structures for all mouse event handlers. This provides strong test coverage for the restored event handling functionality.

test/polar/Radar.spec.tsx (2)

2-2: LGTM! Test helper imports are appropriate.

The addition of fireEvent and test helper utilities aligns with the comprehensive event testing being added.

Also applies to: 11-13


261-378: LGTM! Click and mouse event tests are comprehensive.

The tests properly cover:

  • Click interactions with appropriate assertions
  • Mouse enter/leave with detailed payload validation
  • Mouse over/move/out with multiple move events using fireEvent for fine-grained control

The use of assertNotNull ensures type safety, and expectLastCalledWith provides clear payload assertions.

src/cartesian/Area.tsx (1)

58-59: ✓ Import path verified as correct

The import of svgPropertiesAndEventsFromUnknown from ../util/svgPropertiesAndEvents is correct. The function is properly exported from src/util/svgPropertiesAndEvents.ts (line 41), and the import path in Area.tsx aligns with usage in other files (Radar.tsx, Line.tsx).

test/cartesian/Bar.spec.tsx (1)

33-33: Timers are properly configured—no action needed.

Verification confirms: vi.useFakeTimers() is globally configured at test/vitest.setup.ts:17, userEventSetup() helper properly configures advanceTimers at test/helper/userEventSetup.ts, and Bar.spec.tsx correctly imports and uses userEventSetup(). No async flake risk.

Comment on lines +380 to +394
it('should fire onTouchMove and onTouchEnd events when touching the radar polygon', async () => {
const handleTouchMove = vi.fn();
const handleTouchEnd = vi.fn();

const { container } = render(
<RadarChart width={500} height={500} data={exampleRadarData}>
<Radar dataKey="value" isAnimationActive={false} onTouchMove={handleTouchMove} onTouchEnd={handleTouchEnd} />
</RadarChart>,
);

const polygon = container.querySelector('.recharts-polygon');
assertNotNull(polygon);
fireEvent.touchMove(polygon, { touches: [{ clientX: 200, clientY: 200 }] });
expect(handleTouchMove).toHaveBeenCalledTimes(1);
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Complete the onTouchEnd test coverage.

The test creates handleTouchEnd and passes onTouchEnd to the component but never fires a touchEnd event or asserts the handler was called.

Add this after line 393 to complete the test:

   fireEvent.touchMove(polygon, { touches: [{ clientX: 200, clientY: 200 }] });
   expect(handleTouchMove).toHaveBeenCalledTimes(1);
+
+  fireEvent.touchEnd(polygon);
+  expect(handleTouchEnd).toHaveBeenCalledTimes(1);
 });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it('should fire onTouchMove and onTouchEnd events when touching the radar polygon', async () => {
const handleTouchMove = vi.fn();
const handleTouchEnd = vi.fn();
const { container } = render(
<RadarChart width={500} height={500} data={exampleRadarData}>
<Radar dataKey="value" isAnimationActive={false} onTouchMove={handleTouchMove} onTouchEnd={handleTouchEnd} />
</RadarChart>,
);
const polygon = container.querySelector('.recharts-polygon');
assertNotNull(polygon);
fireEvent.touchMove(polygon, { touches: [{ clientX: 200, clientY: 200 }] });
expect(handleTouchMove).toHaveBeenCalledTimes(1);
});
it('should fire onTouchMove and onTouchEnd events when touching the radar polygon', async () => {
const handleTouchMove = vi.fn();
const handleTouchEnd = vi.fn();
const { container } = render(
<RadarChart width={500} height={500} data={exampleRadarData}>
<Radar dataKey="value" isAnimationActive={false} onTouchMove={handleTouchMove} onTouchEnd={handleTouchEnd} />
</RadarChart>,
);
const polygon = container.querySelector('.recharts-polygon');
assertNotNull(polygon);
fireEvent.touchMove(polygon, { touches: [{ clientX: 200, clientY: 200 }] });
expect(handleTouchMove).toHaveBeenCalledTimes(1);
fireEvent.touchEnd(polygon);
expect(handleTouchEnd).toHaveBeenCalledTimes(1);
});
🤖 Prompt for AI Agents
In test/polar/Radar.spec.tsx around lines 380 to 394, the test registers
handleTouchEnd but never fires or asserts the touchEnd event; after the existing
touchMove firing add a fireEvent.touchEnd call on the same polygon with an
appropriate event payload (e.g., changedTouches/client coords) and then assert
expect(handleTouchEnd).toHaveBeenCalledTimes(1) to verify the handler was
invoked.

@codecov
Copy link

codecov bot commented Oct 25, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.49%. Comparing base (9eb2936) to head (5318073).
⚠️ Report is 5 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6507      +/-   ##
==========================================
+ Coverage   93.45%   93.49%   +0.03%     
==========================================
  Files         431      431              
  Lines       39168    39173       +5     
  Branches     4550     4554       +4     
==========================================
+ Hits        36606    36625      +19     
+ Misses       2545     2531      -14     
  Partials       17       17              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@codecov
Copy link

codecov bot commented Oct 25, 2025

Bundle Report

Changes will increase total bundle size by 192 bytes (0.01%) ⬆️. This is within the configured threshold ✅

Detailed changes
Bundle name Size Change
recharts/bundle-cjs 1.09MB 95 bytes (0.01%) ⬆️
recharts/bundle-es6 939.76kB 90 bytes (0.01%) ⬆️
recharts/bundle-umd 499.77kB 7 bytes (0.0%) ⬆️

Affected Assets, Files, and Routes:

view changes for bundle: recharts/bundle-cjs

Assets Changed:

Asset Name Size Change Total Size Change (%)
cartesian/Area.js 95 bytes 28.21kB 0.34%
view changes for bundle: recharts/bundle-umd

Assets Changed:

Asset Name Size Change Total Size Change (%)
Recharts.js 7 bytes 499.77kB 0.0%
view changes for bundle: recharts/bundle-es6

Assets Changed:

Asset Name Size Change Total Size Change (%)
cartesian/Area.js 90 bytes 26.41kB 0.34%

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants