Testing with SDKs
Build reliable messaging features with testing strategies for Sent SDKs. This guide covers unit testing, integration testing, mocking, and CI/CD best practices.
Testing Pyramid
For messaging integrations, follow this testing strategy:
- Unit Tests (70%) - Mock the SDK, test business logic
- Integration Tests (20%) - Use a dedicated API key for your test environment, with sandbox mode to avoid side effects
- E2E Tests (10%) - Full flow with webhook handling
Unit Testing
Mock the SDK
Don't make real API calls in unit tests:
// __mocks__/@sentdm/sentdm.ts
import { jest } from '@jest/globals';
export const mockSend = jest.fn();
export default jest.fn().mockImplementation(() => ({
messages: {
send: mockSend
}
}));
// notification.service.test.ts
import { mockSend } from './__mocks__/@sentdm/sentdm';
import { NotificationService } from './notification.service';
describe('NotificationService', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should send welcome message on user signup', async () => {
// Arrange
mockSend.mockResolvedValue({
data: {
recipients: [{ message_id: 'msg_123' }],
status: 'QUEUED',
price: 0.0125
}
});
const service = new NotificationService();
const user = { phone: '+1234567890', name: 'John' };
// Act
await service.sendWelcomeMessage(user);
// Assert
expect(mockSend).toHaveBeenCalledWith({
to: ['+1234567890'],
template: {
id: '7ba7b820-9dad-11d1-80b4-00c04fd430c8',
name: 'welcome',
parameters: { name: 'John' }
}
});
});
it('should handle send failures gracefully', async () => {
// Arrange
const error = new Error('Template not found');
error.status = 400;
mockSend.mockRejectedValue(error);
const service = new NotificationService();
const user = { phone: '+1234567890', name: 'John' };
// Act & Assert
await expect(service.sendWelcomeMessage(user))
.rejects.toThrow('Failed to send message');
});
});Testing Error Scenarios
Test all error paths:
const errorScenarios = [
{
name: 'AuthenticationError',
status: 401,
message: 'Should throw on invalid API key',
shouldRetry: false
},
{
name: 'RateLimitError',
status: 429,
message: 'Should retry on rate limit',
shouldRetry: true
},
{
name: 'BadRequestError',
status: 400,
message: 'Should not retry on 4xx',
shouldRetry: false
}
];
errorScenarios.forEach(({ name, status, message, shouldRetry }) => {
it(message, async () => {
const error = new Error('Test error');
(error as any).status = status;
mockSend.mockRejectedValue(error);
const result = await service.sendMessage({...});
expect(result.retryAttempted).toBe(shouldRetry);
});
});Integration Testing
Use a Dedicated API Key per Environment
Use a separate API key for your test/CI environment. There is only one key type, but keeping keys isolated per environment lets you revoke or rotate them independently:
// integration/message.test.ts
import SentDm from '@sentdm/sentdm';
describe('Message Integration Tests', () => {
let client: SentDm;
beforeAll(() => {
// Use test API key
client = new SentDm({ apiKey: process.env.SENT_DM_API_KEY_TEST! });
});
it('should validate message request structure with sandbox mode', async () => {
// Use sandbox mode to validate without sending real messages
const response = await client.messages.send({
to: ['+1234567890'],
template: {
id: '7ba7b820-9dad-11d1-80b4-00c04fd430c8',
name: 'welcome'
},
sandbox: true // Validates but doesn't send
});
// Response will have test data
expect(response.data.recipients[0].message_id).toBeDefined();
expect(response.data.status).toBeDefined();
});
it('should handle invalid template', async () => {
try {
await client.messages.send({
to: ['+1234567890'],
template: {
id: 'non-existent-template',
name: 'invalid'
}
});
fail('Should have thrown');
} catch (error) {
expect(error).toBeInstanceOf(SentDm.BadRequestError);
}
});
});Test Webhooks Locally
Use tools like ngrok or localtunnel for webhook testing. Refer to the local development guide for tunnel setup. To assert on your handler, replay a canonical event envelope with the three signature headers your handler verifies, as described in webhook signature verification:
// webhook.test.ts
describe('Webhook Integration', () => {
let server: Server;
let webhookUrl: string;
beforeAll(async () => {
// Start local server
server = app.listen(3001);
// Create tunnel (using ngrok or similar)
webhookUrl = await createTunnel(3001);
});
afterAll(async () => {
server.close();
await closeTunnel();
});
it('should verify webhook signature', async () => {
const payload = JSON.stringify({
field: 'message',
event: 'message.delivered',
timestamp: '2026-07-25T10:10:42Z',
payload: {
message_id: 'msg_123',
message_status: 'DELIVERED',
channel: 'sms'
}
});
const webhookId = 'wh_test_123';
const timestamp = String(Math.floor(Date.now() / 1000));
// Signed content = "{webhookId}.{timestamp}.{rawBody}"
const signature = generateTestSignature(webhookId, timestamp, payload);
const response = await request(app)
.post('/webhooks/sent')
.set('X-Webhook-ID', webhookId)
.set('X-Webhook-Timestamp', timestamp)
.set('X-Webhook-Signature', signature)
.set('Content-Type', 'application/json')
.send(payload);
expect(response.status).toBe(200);
});
});CI/CD Testing
Environment Setup
Configure separate environments for CI/CD:
# .github/workflows/test.yml
name: Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Run unit tests
run: npm test
- name: Run integration tests
env:
SENT_DM_API_KEY_TEST: ${{ secrets.SENT_DM_API_KEY_TEST }}
run: npm run test:integrationTest Data Management
Use consistent test data:
// test/fixtures.ts
export const testFixtures = {
validPhoneNumber: '+15555551234', // test number
invalidPhoneNumber: 'invalid',
validTemplateId: 'test-welcome-template',
invalidTemplateId: 'non-existent-template',
mockRecipient: {
message_id: 'msg_test_123',
to: '+15555551234',
channel: 'sms'
}
};
// Use in tests
import { testFixtures } from './fixtures';
it('should send to valid number', async () => {
mockSend.mockResolvedValue({
data: {
status: 'QUEUED',
recipients: [testFixtures.mockRecipient]
}
});
const result = await service.sendMessage({
phone: testFixtures.validPhoneNumber
});
expect(mockSend).toHaveBeenCalledWith({
to: [testFixtures.validPhoneNumber],
template: {
id: expect.any(String),
name: expect.any(String)
}
});
});Parallel Test Execution
Ensure tests can run in parallel:
// Use unique identifiers per test
it('should send message', async () => {
const testId = `test-${Date.now()}-${Math.random()}`;
const phoneNumber = `+1555${testId.slice(-7)}`;
mockSend.mockResolvedValue({
data: {
recipients: [{ message_id: `msg_${testId}` }],
status: 'QUEUED'
}
});
const result = await service.sendMessage({ phone: phoneNumber });
expect(result.data.recipients[0].message_id).toBe(`msg_${testId}`);
});Load Testing
Test SDK behavior under load:
Keep sandbox: true in this script. Without it, every run sends (and bills) 100 real messages.
// load-test.ts
import SentDm from '@sentdm/sentdm';
async function loadTest() {
const client = new SentDm({ apiKey: process.env.SENT_DM_API_KEY_TEST! });
const concurrency = 10;
const totalRequests = 100;
console.log(`Starting load test: ${totalRequests} requests at ${concurrency} concurrency`);
const startTime = Date.now();
let successCount = 0;
let errorCount = 0;
for (let batch = 0; batch < totalRequests / concurrency; batch++) {
const promises = Array(concurrency).fill(null).map((_, i) =>
client.messages.send({
to: [`+1555555${String(batch * concurrency + i).padStart(4, '0')}`],
template: {
id: '7ba7b820-9dad-11d1-80b4-00c04fd430c8',
name: 'welcome'
},
sandbox: true // Validates but doesn't send
}).then(() => {
successCount++;
}).catch(err => {
errorCount++;
console.log('Error:', err.message);
})
);
await Promise.all(promises);
}
const duration = Date.now() - startTime;
console.log(`\nResults:`);
console.log(`Duration: ${duration}ms`);
console.log(`Success: ${successCount}`);
console.log(`Errors: ${errorCount}`);
console.log(`RPS: ${(totalRequests / (duration / 1000)).toFixed(2)}`);
}
loadTest();Test Coverage Checklist
Use this checklist to ensure comprehensive test coverage for your messaging integration.
Core Functionality
- Send message with template
- Send message with variables
- Create contact
- Handle successful response
- Handle error response
Error Scenarios
- Invalid API key
- Rate limiting
- Invalid template ID
- Template not approved
- Insufficient credits
- Invalid phone number
- Contact opted out
Webhooks
- Verify webhook signature
- Handle message.delivered
- Handle message.failed
- Handle message.received (inbound replies)
- Handle duplicate events (idempotency)
- Handle invalid signatures
Retry Logic
- Retry on rate limit
- Don't retry on 4xx errors
- Exponential backoff
- Max retry attempts
Edge Cases
- Empty variables object
- Special characters in message
- Very long messages
- Unicode/emojis
- Concurrent requests
Next Steps
- Apply SDK best practices for production error handling, retries, and webhook security
- Resolve common integration errors with the troubleshooting guide
- Set up webhooks to assert on delivery status in end-to-end tests
- Review the language-specific SDK guides for idiomatic examples in your stack
Comprehensive testing ensures your messaging integration works reliably in production. Aim for 80%+ code coverage with a good mix of unit and integration tests.