Open History to see the last commit
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
303}
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._