Create your mocks automagically
npm install @drakensoftware/magicmockThe MagicMock project is no longer maintained.
You can achieve the same functionality (recording and replaying mocks) with PollyJS, which provides a more complete and actively maintained solution.
We recommend migrating to PollyJS for all new and existing projects.
Thank you for using MagicMock! š
---
MagicMock is like a smart recording device for your software tests. Here's what it does in plain terms:
1. First Test Run
- š„ Records what your functions actually do (like real API calls)
- š¾ Saves these recordings as "snapshots"
2. Future Test Runs
- š¼ Plays back the recordings instead of making real calls
- š Makes tests 10x faster (no waiting for real APIs)
- ā
Ensures identical results every time
Example: If your app fetches weather data, MagicMock:
- Records the real weather API response during first test
- Uses that recorded response for all future tests
- No internet needed! No API costs!
---
---
- Automatic Snapshots: Generates mock data on first test run
- Jest-Optimized: Designed specifically for Jest testing workflows
- Argument-Sensitive Mocks: Precise argument matching for accurate test behavior
- Zero Production Overhead: Automatically excluded from production bundles
- Secret Masking: Protect sensitive data in test snapshots
---
bash
npm install magic-mock --save-dev
`$3
`typescript
// test.spec.ts
import { mockFunction } from 'magic-mock';
import { fetchData } from './api';// Create mock
const mockedFetch = mockFunction(this, 'fetchData', fetchData);
test('returns valid data', async () => {
const result = await mockedFetch('https://api.example.com');
expect(result).toMatchSnapshot();
});
`$3
1. Executes real implementation
2. Creates snapshot in __magicMock__ directory
3. Logs: š· Created new snapshot for 'fetchData'$3
1. Uses recorded snapshot
2. Skips real implementation
3. Logs: ⨠Using snapshot for 'fetchData'---
š§ Core Concepts
$3
1. Initial Test Run
- Executes actual function
- Records arguments and response
- Creates .snap file in __magicMock__2. Future Test Runs
- Compares current arguments with snapshots
- Returns recorded response on match
- Creates new snapshot for new argument patterns
$3
- Exact Match Required: Order, type, and value must match
- New Patterns create additional snapshots
- Secret Handling: Use secret() to mask sensitive values
`typescript
import { secret } from 'magic-mock';
const secureFetch = mockFunction(
this,
'authRequest',
(token: string) => secret(token, 'API_TOKEN')
);
`---
š Integration Guide
$3
Embed MagicMock in your library for seamless user experience:`typescript
// your-library.ts
import { mockFunction } from 'magic-mock';export class DataService {
constructor(private fetcher: typeof fetch) {}
async getData(url: string) {
const safeFetch = mockFunction(this, 'safeFetch', this.fetcher);
return safeFetch(url);
}
}
`User Benefits:
- Automatic mocking without setup
- Consistent test behavior across projects
- Transparent snapshot management
$3
Mock third-party APIs not using MagicMock:`typescript
// tests/api.spec.ts
import { externalSDK } from 'third-party';
import { mockFunction } from 'magic-mock';const mockedSDK = mockFunction(
this,
'thirdPartySDK',
externalSDK.initialize
);
test('handles SDK initialization', async () => {
const instance = await mockedSDK({ apiKey: 'test123' });
expect(instance.status).toBe('active');
});
`---
š ļø Advanced Usage
$3
`typescript
import { mockClass } from 'magic-mock';class PaymentProcessor {
async charge(amount: number) { / ... / }
}
const processor = mockClass(new PaymentProcessor(), 'PaymentGateway');
`$3
`typescript
import { callMocked } from 'magic-mock';test('complex test scenario', async () => {
const result = await callMocked(
complexWorkflow,
'custom-scenario-123'
);
// Custom assertions
});
`---
š Best Practices
1. Commit Snapshots
`bash
__magicMock__/
āāā serviceA/
āāā serviceB/
`
- Enables team consistency
- Track snapshot changes via PR reviews2. Snapshot Maintenance
- Delete obsolete snapshots after API changes
- Regenerate when modifying test arguments
3. Selective Mocking
`typescript
// Disable for specific tests
beforeAll(() => {
process.env.DISABLE_MM = 'true';
});
`---
āļø Configuration
$3
| Variable | Default | Description |
|----------|---------|-------------|
| DISABLE_MM | false | Disable all mocking behavior |$3
`
project-root/
āāā __magicMock__/
ā āāā serviceA/
ā ā āāā testDoSomething
ā ā āāā 0
ā ā āāā 1
ā āāā serviceB/
ā āāā testDoAnotherThing
ā āāā 0
ā āāā 1
ā āāā 2
āāā src/
āāā tests/
`---
ā FAQ
Q: How does MagicMock differ from Jest's built-in mocking?
A: Provides automatic snapshot-based mocking without manual mocking implementation.
Q: Can I use it with other test runners?
A: Currently optimized for Jest. Community plugins may enable other runners.
Q: How to handle changing API responses?
A: Delete relevant files and re-run tests to regenerate.
---

`markdown

``---
Upgrade Your Jest Testing - MagicMock eliminates manual mock maintenance while ensuring test consistency. Start focusing on what matters - your test logic! š