Testing & Debugging
Learn how to effectively test and debug your ToughClicks integration using built-in debugging tools and best practices.
Overview
ToughClicks provides comprehensive debugging capabilities to help you develop and troubleshoot your integration. This guide covers:
- Debug mode configuration
- State inspection
- Common debugging scenarios
- Testing strategies
- Browser developer tools integration
Debug Mode
Debug mode enables detailed console logging throughout the ToughClicks library, helping you understand what's happening at each step.
Enabling Debug Mode
During Initialization
import { ToughClicks } from '@toughclicks/js-client-sdk';
const tc = new ToughClicks(
clientToken,
packetId,
true // Enable debug mode
);
After Initialization
const tc = new ToughClicks(clientToken, packetId);
// Enable debug mode later
tc.setDebug(true);
Disable Debug Mode
tc.setDebug(false);
What Debug Mode Logs
When debug mode is enabled, you'll see console logs for:
- Initialization - Library setup and configuration
- API Requests - All HTTP requests to ToughClicks servers
- API Responses - Response data and status codes
- State Changes - Updates to internal state
- Validation Events - Checkbox validation results
- Acceptance Events - User acceptance actions
- Rendering - UI rendering steps
- Errors - Detailed error information
Example Debug Output
tc.setDebug(true);
tc.render();
// Console output:
// [ToughClicks Debug] Initializing with client token: 477951a5-...
// [ToughClicks Debug] Fetching packet data for: 3646a13b-...
// [ToughClicks Debug] API Request: GET /api/packets/3646a13b-...
// [ToughClicks Debug] API Response: 200 OK
// [ToughClicks Debug] Packet contains 2 documents
// [ToughClicks Debug] Rendering documents in container: tc-agreements
// [ToughClicks Debug] Validation state: invalid (0/2 documents accepted)
State Inspection
Print Current State
The printState() method outputs the current internal state to the console:
tc.printState();
This displays:
- Current configuration
- Loaded packets and documents
- User acceptance status
- Validation state
- Display options
- Dynamic data (if set)
Example State Output
tc.printState();
// Console output:
// [ToughClicks State] {
// clientToken: "477951a5-069b-401f-ab7f-32db486d5741",
// environment: "production",
// debug: true,
// packets: [
// {
// id: "3646a13b-cbd1-482c-9947-460cb74a71f2",
// name: "User Agreements",
// documents: [
// { id: "doc-1", name: "Terms of Service", accepted: false },
// { id: "doc-2", name: "Privacy Policy", accepted: true }
// ]
// }
// ],
// displayOptions: {
// containerId: "tc-agreements",
// signerId: "[email protected]",
// displayMethod: "individual",
// shouldOpenModal: true
// },
// isValid: false,
// allAccepted: false
// }
Check Validation State
// Get current validation state
const isValid = tc.isValid();
console.log('Form is valid:', isValid);
// Check specific packet
const packetValid = tc.isPacketValid('packet-id');
console.log('Packet is valid:', packetValid);
Testing Strategies
1. Local Development Testing
Use debug mode and sandbox environment during development:
import { ToughClicks, TCEnvironment } from '@toughclicks/js-client-sdk';
const isDevelopment = process.env.NODE_ENV === 'development';
const tc = new ToughClicks(
process.env.VITE_TC_CLIENT_TOKEN,
process.env.VITE_TC_PACKET_ID,
isDevelopment, // Debug on in development
isDevelopment ? TCEnvironment.staging : TCEnvironment.production
);
if (isDevelopment) {
// Log state after every render
tc.render().then(() => {
tc.printState();
});
}
2. Event Debugging
Monitor all events to understand the flow:
import { TCEventTypes } from '@toughclicks/js-client-sdk';
tc.setDebug(true);
// Log all validation events
tc.on(TCEventTypes.valid, (event) => {
console.log('Validation event:', event.detail);
console.log('Is valid:', event.detail.isValid);
console.log('Validated packets:', event.detail.validatedPackets);
});
// Log all acceptance events
tc.on(TCEventTypes.accepted, (event) => {
console.log('Acceptance event:', event.detail);
console.log('All accepted:', event.detail.allAccepted);
console.log('Accepted documents:', event.detail.acceptances);
});
// Log all error events
tc.on(TCEventTypes.error, (event) => {
console.error('ToughClicks error:', event.detail);
});
// Log initialization
tc.on(TCEventTypes.initialized, (event) => {
console.log('ToughClicks initialized:', event.detail);
tc.printState();
});
3. Visual Debugging
Add visual indicators for debugging:
tc.on(TCEventTypes.valid, (event) => {
const indicator = document.getElementById('debug-indicator');
if (indicator) {
indicator.style.background = event.detail.isValid ? 'green' : 'red';
indicator.textContent = event.detail.isValid ? 'Valid' : 'Invalid';
}
});
<div id="debug-indicator" style="
position: fixed;
top: 10px;
right: 10px;
padding: 10px;
background: red;
color: white;
border-radius: 4px;
z-index: 10000;
">
Initializing...
</div>
4. Network Debugging
Monitor API calls using browser DevTools:
// Enable debug mode to see API logs
tc.setDebug(true);
// In browser DevTools:
// 1. Open Network tab
// 2. Filter by "toughclicks"
// 3. Inspect request/response details
// 4. Check for errors or slow responses
Common Debugging Scenarios
Scenario 1: Checkboxes Not Rendering
Problem: ToughClicks UI doesn't appear.
Debug Steps:
tc.setDebug(true);
// Check if container exists
const container = document.getElementById('tc-agreements');
console.log('Container found:', !!container);
// Check if packet loaded
tc.render().then((success) => {
console.log('Render successful:', success);
tc.printState();
}).catch((error) => {
console.error('Render error:', error);
});
// Listen for errors
tc.on(TCEventTypes.error, (event) => {
console.error('ToughClicks error:', event.detail);
});
Common Causes:
- Container element doesn't exist
- Invalid client token or packet ID
- Packet has no published documents
- CSS not loaded
Scenario 2: Validation Not Working
Problem: Form validation isn't responding to checkbox changes.
Debug Steps:
tc.setDebug(true);
// Monitor validation events
tc.on(TCEventTypes.valid, (event) => {
console.log('Validation event received');
console.log('Is valid:', event.detail.isValid);
console.log('Event detail:', event.detail);
});
// Manually trigger validation check
tc.on(TCEventTypes.checkboxChanged, (event) => {
console.log('Checkbox changed:', event.detail);
setTimeout(() => {
console.log('Current validation state:', tc.isValid());
tc.printState();
}, 100);
});
Common Causes:
- Not listening for the right event
- Event listener added after render
- Multiple ToughClicks instances
Scenario 3: Acceptance Not Creating
Problem: User checks boxes but acceptance doesn't create.
Debug Steps:
tc.setDebug(true);
// Check manual acceptance setting
tc.setDisplayOptions({
containerId: 'tc-agreements',
signerId: '[email protected]',
manualAcceptance: false // Should be false for automatic
});
// Monitor acceptance events
tc.on(TCEventTypes.accepted, (event) => {
console.log('Acceptance event:', event.detail);
});
tc.on(TCEventTypes.error, (event) => {
console.error('Error during acceptance:', event.detail);
});
// If using manual acceptance, ensure you call accept()
if (manualAcceptanceEnabled) {
tc.accept().then((result) => {
console.log('Manual acceptance result:', result);
});
}
Common Causes:
- Manual acceptance enabled
- Missing signer ID
- Network error during submission
- Invalid custom data
Scenario 4: Dynamic Data Not Rendering
Problem: Dynamic contract variables not showing.
Debug Steps:
tc.setDebug(true);
// Verify data is set before render
const dynamicData = {
user: { name: 'John Doe', email: '[email protected]' }
};
console.log('Setting dynamic data:', dynamicData);
tc.setDynamicData(dynamicData);
// Confirm state includes dynamic data
tc.printState();
// Then render
tc.render().then(() => {
console.log('Rendered with dynamic data');
});
Common Causes:
setDynamicData()called afterrender()- Data structure doesn't match template
- Template syntax errors in document
Scenario 5: Multiple Packets Issues
Problem: Multiple packet rendering or validation not working.
Debug Steps:
tc.setDebug(true);
const packetIds = ['packet-1', 'packet-2', 'packet-3'];
tc.on(TCEventTypes.initialized, (event) => {
console.log('Initialized packets:', event.detail.packets);
tc.printState();
});
tc.on(TCEventTypes.valid, (event) => {
console.log('Validation by packet:');
event.detail.validatedPackets.forEach((packet) => {
console.log(`- ${packet.id}: ${packet.isValid ? 'Valid' : 'Invalid'}`);
});
});
// Check individual packet validity
packetIds.forEach((packetId) => {
const isValid = tc.isPacketValid(packetId);
console.log(`Packet ${packetId} is valid:`, isValid);
});
Browser Developer Tools
Console Filtering
Filter console output to focus on ToughClicks:
// Chrome/Firefox DevTools Console filter:
ToughClicks
// Or use custom prefix for your logs:
const log = (message, ...args) => {
console.log('[MyApp:TC]', message, ...args);
};
tc.on(TCEventTypes.valid, (event) => {
log('Validation changed:', event.detail.isValid);
});
Network Tab
Monitor API calls:
- Open DevTools > Network tab
- Enable debug mode:
tc.setDebug(true) - Filter by "toughclicks.com" or "stage.toughclicks.com"
- Inspect requests:
- Check request headers
- Verify authentication token
- Examine response data
- Look for errors (4xx, 5xx status codes)
Breakpoints
Set breakpoints in event handlers:
tc.on(TCEventTypes.valid, (event) => {
debugger; // Execution will pause here
console.log('Validation state:', event.detail);
});
Performance Profiling
Profile rendering performance:
console.time('ToughClicks Render');
tc.render().then(() => {
console.timeEnd('ToughClicks Render');
});
Testing Checklist
Before going to production, test:
Basic Functionality
- Library initializes without errors
- Checkboxes render correctly
- Clicking checkboxes works
- Validation events fire
- Acceptance creates successfully
- Error handling works
Edge Cases
- Empty packet (no documents)
- Single document packet
- Multiple document packet
- Multiple packets
- Missing signer ID
- Invalid credentials
- Network failures
Browser Compatibility
- Chrome (latest 2 versions)
- Firefox (latest 2 versions)
- Safari (latest 2 versions)
- Edge (latest 2 versions)
- Mobile browsers (iOS Safari, Chrome Mobile)
Integration Points
- Works with your authentication
- Integrates with form validation
- Submits with form data
- Handles page reloads
- Works with SPA navigation
Performance
- Initial render time < 500ms
- No console errors
- No memory leaks
- Works with slow network (3G simulation)
Production Debugging
Disable Debug in Production
Always disable debug mode in production:
const tc = new ToughClicks(
clientToken,
packetId,
false // Debug disabled
);
Error Monitoring
Implement error monitoring in production:
tc.on(TCEventTypes.error, (event) => {
// Send to error tracking service
if (window.Sentry) {
Sentry.captureException(new Error(event.detail.message), {
extra: {
toughClicksError: event.detail,
userId: currentUserId,
packetId: packetId
}
});
}
// Or log to your backend
fetch('/api/log-error', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
service: 'toughclicks',
error: event.detail,
timestamp: new Date().toISOString()
})
});
});
Conditional Debugging
Enable debugging for specific users or conditions:
const shouldDebug =
window.location.search.includes('debug=true') ||
localStorage.getItem('tc_debug') === 'true' ||
userIsAdmin;
const tc = new ToughClicks(
clientToken,
packetId,
shouldDebug
);
Best Practices
1. Remove Debug Code Before Production
// Development
if (process.env.NODE_ENV === 'development') {
tc.setDebug(true);
tc.printState();
}
// Don't do this in production:
// tc.setDebug(true); // ❌ Remove!
// tc.printState(); // ❌ Remove!
2. Use Meaningful Console Messages
tc.on(TCEventTypes.valid, (event) => {
console.log('[Signup Form] ToughClicks validation:', {
isValid: event.detail.isValid,
timestamp: new Date().toISOString()
});
});
3. Test Error Scenarios
Deliberately test error cases:
// Test with invalid token
const tc = new ToughClicks('invalid-token', packetId, true);
// Test with non-existent packet
const tc = new ToughClicks(clientToken, 'non-existent-id', true);
// Test with missing container
tc.setDisplayOptions({ containerId: 'non-existent-element' });
4. Document Your Debugging Findings
Keep notes on common issues and solutions:
/**
* ToughClicks Debugging Notes
*
* Issue: Checkboxes not rendering
* Solution: Ensure container exists before calling render()
*
* Issue: Validation not firing in React
* Solution: Use useEffect to set up event listeners only once
*
* Issue: Acceptance fails silently
* Solution: Check network tab, usually missing signer ID
*/
Troubleshooting Resources
- Enable Debug Mode - Always your first step
- Check Console - Look for errors or warnings
- Inspect Network - Verify API calls succeed
- Use printState() - Understand current state
- Test in Isolation - Create minimal reproduction
- Contact Support - Include debug logs when reporting issues
Next Steps
- Set up sandbox environments for safe testing
- Implement force reacceptance workflows
- Learn about migration strategies for API updates