Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

DEBUGGING.md

334 lines8.5 KB

1# Debugging & Testing Guide
2​
3_A practical guide for debugging complex issues and running tests effectively, learned from investigating production regressions in large codebases._
4​
5## Quick Start Debugging Checklist
6​
7When you encounter a bug report or failing test:
8​
91. **Reproduce first** - Create a minimal test case that demonstrates the exact issue
102. **Establish baseline** - Run existing tests to see what currently works/breaks
113. **Add targeted logging** - Insert debug output at key decision points
124. **Trace the data flow** - Follow the path from input to unexpected output
135. **Check recent changes** - Look for version changes mentioned in bug reports
146. **Test your hypothesis** - Make small, targeted changes and validate each step
15​
16## Essential Testing Commands
17​
18### Monorepo with Nx
19​
20```bash
21# Run all tests for a package
22npx nx test:unit @package-name
23​
24# Run specific test file
25npx nx test:unit @package-name -- --run path/to/test.test.tsx
26​
27# Run tests matching a pattern
28npx nx test:unit @package-name -- --run "pattern-in-test-name"
29​
30# Run with verbose output
31npx nx test:unit @package-name -- --run --verbose
32```
33​
34### Standard npm/yarn projects
35​
36```bash
37# Run specific test file
38npm test -- --run path/to/test.test.tsx
39yarn test path/to/test.test.tsx
40​
41# Run tests matching pattern
42npm test -- --grep "test pattern"
43```
44​
45### Useful test flags
46​
47```bash
48# Run only (don't watch for changes)
49--run
50​
51# Show full output including console.logs
52--verbose
53​
54# Run in specific environment
55--environment=jsdom
56```
57​
58## Effective Debugging Strategies
59​
60### 1. Strategic Logging
61​
62```javascript
63// Use distinctive prefixes for easy filtering
64console.log('[DEBUG useNavigate] from:', from, 'to:', to)
65console.log('[DEBUG router] current location:', state.location.pathname)
66​
67// Log both input and output of functions
68console.log('[DEBUG buildLocation] input:', dest)
69// ... function logic ...
70console.log('[DEBUG buildLocation] output:', result)
71```
72​
73**Pro tip:** Use `[DEBUG componentName]` prefixes so you can easily filter logs in browser dev tools.
74​
75### 2. Reproduction Test Pattern
76​
77```javascript
78test('should reproduce the exact issue from bug report', async () => {
79 // Set up the exact scenario described
80 const router = createRouter({
81 /* exact config from bug report */
82 })
83​
84 // Perform the exact user actions
85 await navigate({ to: '/initial-route' })
86 await navigate({ to: '.', search: { param: 'value' } })
87​
88 // Assert the expected vs actual behavior
89 expect(router.state.location.pathname).toBe('/expected')
90 // This should fail initially, proving reproduction
91})
92```
93​
94### 3. Data Flow Tracing
95​
96```
97User Action β†’ Hook Call β†’ Router Logic β†’ State Update β†’ UI Update
98 ↓ ↓ ↓ ↓ ↓
99 onClick() β†’ useNavigate() β†’ buildLocation() β†’ setState() β†’ re-render
100```
101​
102Add logging at each step to see where the flow diverges from expectations.
103​
104## Common Pitfalls & Solutions
105​
106### React Testing Issues
107​
108**Problem:** State updates not reflected in tests
109​
110```javascript
111// ❌ Bad - missing act() wrapper
112fireEvent.click(button)
113expect(component.state).toBe(newValue)
114​
115// βœ… Good - wrapped in act()
116act(() => {
117 fireEvent.click(button)
118})
119expect(component.state).toBe(newValue)
120```
121​
122**Problem:** Async operations not completing
123​
124```javascript
125// ❌ Bad - not waiting for async
126const result = await someAsyncOperation()
127expect(result).toBe(expected)
128​
129// βœ… Good - ensuring completion
130await act(async () => {
131 await someAsyncOperation()
132})
133expect(result).toBe(expected)
134```
135​
136### React Router Specific Issues
137​
138**Context vs Location confusion:**
139​
140- `useMatch({ strict: false })` returns the **component's route context**
141- `router.state.location.pathname` returns the **current URL**
142- These can be different when components are rendered by parent routes
143​
144```javascript
145// Component rendered by parent route "/" but URL is "/child"
146const match = useMatch({ strict: false }) // Returns "/" context
147const location = router.state.location.pathname // Returns "/child"
148```
149​
150## Search & Investigation Commands
151​
152### Finding relevant code
153​
154```bash
155# Search for specific patterns in TypeScript/JavaScript files
156grep -r "navigate.*to.*\." --include="*.ts" --include="*.tsx" .
157​
158# Find files related to a feature
159find . -name "*navigate*" -type f
160​
161# Search with ripgrep (faster)
162rg "useNavigate" --type typescript
163```
164​
165### Git investigation
166​
167```bash
168# Find when a specific line was changed
169git blame path/to/file.ts
170​
171# See recent changes to a file
172git log --oneline -10 path/to/file.ts
173​
174# Search commit messages
175git log --grep="navigation" --oneline
176```
177​
178## Testing Best Practices
179​
180### Test Structure
181​
182```javascript
183describe('Feature', () => {
184 beforeEach(() => {
185 // Reset state for each test
186 cleanup()
187 history = createBrowserHistory()
188 })
189​
190 test('should handle specific scenario', async () => {
191 // Arrange - set up the test conditions
192 const router = createRouter(config)
193​
194 // Act - perform the action being tested
195 await act(async () => {
196 navigate({ to: '/target' })
197 })
198​
199 // Assert - verify the results
200 expect(router.state.location.pathname).toBe('/target')
201 })
202})
203```
204​
205### Multiple Assertions
206​
207```javascript
208test('navigation should update both path and search', async () => {
209 await navigate({ to: '/page', search: { q: 'test' } })
210​
211 // Test multiple aspects
212 expect(router.state.location.pathname).toBe('/page')
213 expect(router.state.location.search).toEqual({ q: 'test' })
214 expect(router.state.matches).toHaveLength(2)
215})
216```
217​
218## Architecture Investigation Process
219​
220### 1. Map the System
221​
222```
223User Input β†’ Component β†’ Hook β†’ Core Logic β†’ State β†’ UI
224```
225​
226Identify each layer and what it's responsible for.
227​
228### 2. Find the Divergence Point
229​
230Use logging to identify exactly where expected behavior diverges:
231​
232```javascript
233console.log('Input received:', input)
234// ... processing ...
235console.log('After step 1:', intermediate)
236// ... more processing ...
237console.log('Final output:', output) // Is this what we expected?
238```
239​
240### 3. Check Assumptions
241​
242Common false assumptions:
243​
244- "This hook returns the current route" (might return component context)
245- "State updates are synchronous" (often async in React)
246- "This worked before" (check if tests actually covered this case)
247​
248## Regression Investigation
249​
250### Version Comparison
251​
252```bash
253# Check what changed between versions
254git diff v1.120.13..v1.121.34 -- packages/react-router/
255​
256# Look for specific changes
257git log v1.120.13..v1.121.34 --oneline --grep="navigate"
258```
259​
260### Bisecting Issues
261​
262```bash
263# Start bisect to find breaking commit
264git bisect start
265git bisect bad HEAD
266git bisect good v1.120.13
267​
268# Test each commit until you find the breaking change
269```
270​
271## When to Stop & Reconsider
272​
273**Stop changing code when:**
274​
275- Your fix breaks multiple existing tests
276- You're changing fundamental assumptions
277- The solution feels hacky or overly complex
278​
279**Consider instead:**
280​
281- Adding a new API rather than changing existing behavior
282- Documenting the current behavior if it's actually correct
283- Creating a more targeted fix for the specific use case
284​
285## Advanced Debugging Techniques
286​
287### React DevTools
288​
289- Inspect component tree to understand render context
290- Check props and state at each level
291- Use Profiler to identify performance issues
292​
293### Browser DevTools
294​
295```javascript
296// Add global debugging helpers
297window.debugRouter = router
298window.debugState = () => console.log(router.state)
299​
300// Use conditional breakpoints
301if (router.state.location.pathname === '/problematic-route') {
302 debugger
304```
305​
306### Test Isolation
307​
308```javascript
309// Run only one test to isolate issues
310test.only('this specific failing test', () => {
311 // ...
312})
313​
314// Skip problematic tests temporarily
315test.skip('temporarily disabled', () => {
316 // ...
317})
318```
319​
320## Key Takeaways
321​
3221. **Reproduction beats theory** - A failing test that demonstrates the issue is worth more than understanding the problem in theory
323​
3242. **Existing tests are protection** - If your fix breaks many existing tests, you're probably changing the wrong thing
325​
3263. **Context matters** - Especially in React, understanding where components are rendered and what context they have access to is crucial
327​
3284. **Small changes, frequent validation** - Make small, targeted changes and test each one rather than large refactors
329​
3305. **Sometimes the answer is "don't change it"** - Not every reported issue needs a code change; sometimes documentation or a new API is the right solution
331​
332---
333​
334_This guide was developed while investigating a navigation regression in TanStack Router, where `navigate({ to: "." })` unexpectedly redirected to the root instead of staying on the current route._