Part 3: Development, Testing, and Code Quality
Introduction
Actually Writing Code
The Development Flow
Step 1: Write the Test First
// tests/unit/webhookHandler.test.ts
import { describe, it, expect, vi } from 'vitest';
import { WebhookHandler } from '../../src/services/webhookHandler';
import crypto from 'crypto';
describe('WebhookHandler', () => {
const handler = new WebhookHandler({
secret: 'whsec_test_secret',
});
describe('verifySignature', () => {
it('should accept valid Stripe signature', () => {
const payload = JSON.stringify({ type: 'payment_intent.succeeded' });
const timestamp = Math.floor(Date.now() / 1000);
// Create valid signature
const signedPayload = `${timestamp}.${payload}`;
const signature = crypto
.createHmac('sha256', 'whsec_test_secret')
.update(signedPayload)
.digest('hex');
const headers = {
'stripe-signature': `t=${timestamp},v1=${signature}`,
};
expect(() => handler.verifySignature(payload, headers)).not.toThrow();
});
it('should reject invalid signature', () => {
const payload = JSON.stringify({ type: 'payment_intent.succeeded' });
const headers = {
'stripe-signature': 't=123456789,v1=invalidsignature',
};
expect(() => handler.verifySignature(payload, headers))
.toThrow('Invalid signature');
});
it('should reject expired timestamps (>5 min old)', () => {
const payload = JSON.stringify({ type: 'payment_intent.succeeded' });
const oldTimestamp = Math.floor(Date.now() / 1000) - 400; // 6 mins ago
const signedPayload = `${oldTimestamp}.${payload}`;
const signature = crypto
.createHmac('sha256', 'whsec_test_secret')
.update(signedPayload)
.digest('hex');
const headers = {
'stripe-signature': `t=${oldTimestamp},v1=${signature}`,
};
expect(() => handler.verifySignature(payload, headers))
.toThrow('Timestamp too old');
});
});
});Step 2: Implement Minimum Code
Step 3: Refactor
The Fastify Route Handler
Testing & Debugging
Testing Strategy
Unit Tests (Continued)
Integration Tests
Debugging Techniques
1. Strategic Console Logging
2. VS Code Debugger
3. Request Replay Debugging
4. Error Tracking with Sentry
Browser Automation
Setup
Visual Regression Testing
Code Review
My Code Review Checklist
What I Look For
1. Correctness
2. Test Coverage
3. Security
4. Performance
My Code Review Comments (Examples)
Key Takeaways
What's Next
PreviousPart 2: Planning, Architecture, and Project SetupNextPart 4: API Development and Integrations
Last updated