
Security News
Attackers Are Hunting High-Impact Node.js Maintainers in a Coordinated Social Engineering Campaign
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.
ts-smart-mocker
Advanced tools
A TypeScript-based API mocking library for seamless development and testing
A powerful TypeScript-based API mocking library for seamless development and testing.
npm install ts-api-mocker
import { ApiMocker } from 'ts-api-mocker';
// Create an instance with default settings
const apiMocker = new ApiMocker();
// Use smartFetch instead of fetch
async function getData() {
const response = await apiMocker.smartFetch('https://api.example.com/data');
return await response.json();
}
const apiMocker = new ApiMocker({
// Enable or disable mocking (default: false)
isMocking: true,
// Store real API responses for future mocking (default: false)
storeRealResponses: true,
// Store error responses (default: false)
storeErrorResponses: true,
// Default delay in milliseconds for mocked responses (default: 1000)
defaultDelay: 500
});
Create a .env.development file:
MOCKING_ENABLED=true
MOCKING_DELAY=1000
MOCKING_STORE_REAL_API_CALL=true
MOCKING_SAVE_ERROR_RESPONSE=true
Work on frontend features without waiting for backend APIs to be ready.
// Initialize with mocking enabled
const apiMocker = new ApiMocker({ isMocking: true });
// First, record a real response (or manually create mock data)
async function setupMocks() {
// This will store the response for future use
await apiMocker.smartFetch('https://api.example.com/users');
}
// Later in your application code
async function getUsers() {
// This will return the mocked data when mocking is enabled
const response = await apiMocker.smartFetch('https://api.example.com/users');
return await response.json();
}
Create reliable tests that don't depend on external services.
// In your test setup
const apiMocker = new ApiMocker({
isMocking: true,
storeRealResponses: false // Don't overwrite existing mocks during tests
});
// Test a component that makes API calls
test('displays user data correctly', async () => {
// Your component uses apiMocker.smartFetch internally
const component = render(<UserList />);
// Assert that the component displays the mocked data correctly
await waitFor(() => {
expect(component.getByText('John Doe')).toBeInTheDocument();
});
});
Test how your application handles API errors.
// Enable error response storage
const apiMocker = new ApiMocker({
isMocking: true,
storeErrorResponses: true
});
// Store an error response
async function setupErrorMock() {
try {
// This will fail and store the error
await apiMocker.smartFetch('https://api.example.com/invalid-endpoint');
} catch (error) {
console.log('Error captured for future mocking');
}
}
// Test error handling in your application
async function testErrorHandling() {
try {
const data = await fetchUserData(); // Uses apiMocker internally
} catch (error) {
// Handle the error appropriately
showErrorMessage(error.message);
}
}
Toggle mocking on and off during application execution.
const apiMocker = new ApiMocker();
// Enable mocking for specific operations
function enterOfflineMode() {
apiMocker.enableMocking();
updateUIForOfflineMode();
}
// Disable mocking to use real APIs
function goOnline() {
apiMocker.disableMocking();
updateUIForOnlineMode();
}
// Toggle real response storage
function toggleDataCapture(enabled) {
if (enabled) {
apiMocker.enableRealResponseStorage();
} else {
apiMocker.disableRealResponseStorage();
}
}
Use as a mock server during API development.
// In your API development environment
const apiMocker = new ApiMocker({
isMocking: true,
defaultDelay: 300 // Faster responses during development
});
// Add custom mock responses
apiMocker.addMock({
endpoint: '/api/users',
method: 'GET',
response: {
users: [
{ id: 1, name: 'Alice', role: 'Admin' },
{ id: 2, name: 'Bob', role: 'User' }
],
total: 2
},
delay: 500 // Custom delay for this endpoint
});
// Your API endpoint implementation
app.get('/api/users', async (req, res) => {
// During development, this will return the mock
// In production, it will call the real database
const response = await apiMocker.smartFetch('/api/users');
const data = await response.json();
res.json(data);
});
ApiMocker// Create a new instance
const apiMocker = new ApiMocker(options);
smartFetch(input, init)Similar to the standard fetch API but with mocking capabilities.
enableMocking() / disableMocking()Toggle mocking on or off.
enableRealResponseStorage() / disableRealResponseStorage()Toggle storing of real API responses.
enableErrorResponseStorage() / disableErrorResponseStorage()Toggle storing of error responses.
addMock(config)Add a custom mock configuration.
getStoredResponse(url, method, requestBody?)Retrieve a stored response.
getStoredResponses()Get all stored responses.
clearStoredResponses()Clear all stored responses.
Access current configuration via the config property:
const currentConfig = apiMocker.config;
console.log('Mocking enabled:', currentConfig.isMocking);
console.log('Store real responses:', currentConfig.storeRealResponses);
console.log('Store error responses:', currentConfig.storeErrorResponses);
console.log('Default delay:', currentConfig.defaultDelay);
Contributions are welcome! Please feel free to submit a Pull Request.
MIT
FAQs
A TypeScript-based API mocking library for seamless development and testing
We found that ts-smart-mocker demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Multiple high-impact npm maintainers confirm they have been targeted in the same social engineering campaign that compromised Axios.

Security News
Axios compromise traced to social engineering, showing how attacks on maintainers can bypass controls and expose the broader software supply chain.

Security News
Node.js has paused its bug bounty program after funding ended, removing payouts for vulnerability reports but keeping its security process unchanged.