@laigma/mock-db
v1.2.5
Published
In-memory database for functional tests
Maintainers
Readme
🗄️ MockDB
Lightweight in-memory database + API mocker for testing
📋 Overview
@laigma/mock-db is a modular toolkit for mocking data in tests. It ships two independent pieces:
| Export | Purpose |
|---|---|
| MockDb | Loads JSON files into an in-memory store. Core of the library. |
| createApiMocker | Axios interceptor plugin. Intercepts requests and returns mock data from a MockDb instance. Requires axios and a @laigma/logger BackendLogger. |
🚀 Installation
npm install @laigma/mock-dbIf you use the createApiMocker plugin, also install:
npm install axios @laigma/logger📖 MockDb
Setup
Create a directory with one JSON file per collection. The filename (without .json) becomes the key in the database.
mocks/
users.json
products.jsonInitialization
import MockDb from "@laigma/mock-db";
import path from "path";
const db = new MockDb();
db.init(path.resolve(__dirname, "./mocks")); // silent
db.init(path.resolve(__dirname, "./mocks"), true); // with colored ANSI logPassing true as the second argument prints a visual summary to the terminal:
════════════════════════════════════════════════════════════
🗄️ MockDB - In-Memory Database
════════════════════════════════════════════════════════════
✓ Status: READY
📊 Loaded Collections: 2
Available Collections:
1. users
2. products
════════════════════════════════════════════════════════════API
init(jsonDirectory: string, enableLogging?: boolean): void
Reads every .json file in jsonDirectory and stores the parsed content using the filename (without extension) as the key. Throws if the directory does not exist.
getDb(): Record<string, unknown>
Returns a shallow copy of the entire in-memory store.
const snapshot = db.getDb();getData(key: string): unknown
Returns the value stored under key, or undefined if not found.
const users = db.getData("users");setData(key: string, value: unknown): void
Inserts or overwrites a key in the store.
db.setData("session", { token: "abc123" });🔌 createApiMocker plugin
An Axios interceptor that short-circuits outgoing requests and returns mock data instead of hitting the network.
How it works
- The request interceptor checks whether the request URL contains any registered key.
- Match — resolves with a synthetic
200response containing the mock data. - No match — calls
logger.logError(when debug is active) and rejects with anError.
Usage
import axios from "axios";
import MockDb, { createApiMocker } from "@laigma/mock-db";
import { createBackendLogger } from "@laigma/logger";
import path from "path";
const db = new MockDb();
db.init(path.resolve(__dirname, "./mocks"));
const logger = createBackendLogger({
envMode: process.env.NODE_ENV,
appName: "my-app",
appVersion: "1.0.0",
});
const axiosInstance = axios.create({ baseURL: "https://api.example.com" });
createApiMocker({
responses: {
"/api/users": db.getData("users"),
"/api/products": db.getData("products"),
},
logger,
envMode: process.env.NODE_ENV, // "production" throws immediately
}).attachTo(axiosInstance);ApiMockerOptions
| Property | Type | Required | Description |
|---|---|---|---|
| responses | Record<string, unknown> | ✅ | Map of URL fragment → mock data. Values are typically obtained via db.getData(key). |
| logger | IBackendLogger | ✅ | Instance of BackendLogger from @laigma/logger. |
| envMode | string | — | Application environment (e.g. "development", "test"). Passing "production" throws immediately — mocking in production is forbidden. Also controls the debug default when not set explicitly. |
| debug | boolean | — | Enable/disable logger output. When omitted, defaults to false if envMode === "test", true otherwise. Passing debug: false suppresses all logger calls without disabling the interceptors. |
debug / envMode behaviour matrix
| envMode | debug | Logger calls |
|---|---|---|
| "production" | any | throws at construction |
| "test" | (unset) | silent |
| "development" | (unset) | active |
| (unset) | (unset) | active |
| any | true | active |
| any | false | silent |
Even when
debug: false, an unmatched route still rejects with anError.
IBackendLogger (structural interface)
The plugin accepts any object that satisfies this shape — no hard dependency on @laigma/logger at the type level:
interface IBackendLogger {
logError(message: string, errorObj: unknown, metadata?: LogMetadata, stopProcess?: boolean): void;
logSuccess(message: string, detailObj?: unknown, metadata?: LogMetadata): void;
}💡 Full example
import MockDb, { createApiMocker } from "@laigma/mock-db";
import { createBackendLogger } from "@laigma/logger";
import axios from "axios";
import path from "path";
const db = new MockDb();
db.init(path.resolve(__dirname, "./mocks"), true);
const logger = createBackendLogger({
envMode: process.env.NODE_ENV,
appName: "my-app",
appVersion: "1.0.0",
});
createApiMocker({
responses: {
"/users": db.getData("users"),
"/posts": db.getData("posts"),
},
logger,
envMode: process.env.NODE_ENV, // throws if NODE_ENV === "production"
// debug: false // override logging regardless of envMode
}).attachTo(axios.create({ baseURL: "https://api.example.com" }));🛠️ Development
npm install
# Run tests
npm test
# Watch mode
npm run test:watch
# Coverage
npm run test:coverage
# Human-readable demo (no tests)
npm run demo
# Build
npm run buildProject structure
src/
core/
MockDb.ts ← in-memory store
plugins/
apiMocker.ts ← createApiMocker plugin
index.ts ← public entry point
tests/
MockDb.test.ts
MockDb.logging.test.ts
apiMocker.test.ts
fixtures/ ← JSON test data
demo/
index.ts ← standalone human-debug script
mocks/ ← demo JSON fixtures🤝 Contributions
Contributions are welcome! Please feel free to submit a Pull Request or open an Issue.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the ISC License. See the LICENSE file for more details.
Made with ❤️ by laigma
