Registry / testing / miragejs

miragejs

JSON →
library0.1.48jsnpmunverified

Mirage JS is a client-side server library for JavaScript applications, designed to mock API requests during development, testing, and prototyping. It intercepts network requests (XHR and Fetch) and returns defined responses, allowing front-end development to proceed independently of a live backend. The current stable version is 0.1.48, with an experimental 0.2.x alpha branch actively exploring integration with MSW as an alternative interceptor to the default Pretender. Mirage JS is distinguished by its full-featured ORM-like data layer, including models, factories, and serializers, which enables complex data relationships and realistic mock API interactions, setting it apart from simpler request mocking tools. Its release cadence appears to be several patches per month on the 0.1.x branch, with larger architectural changes being developed in the 0.2.x alpha line.

npm install miragejs
INSTALL
IMPORT
SIG · MIRAGEJS
M
miragejs
testingjavascriptv0.1.48
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

createServer
import { createServer } from 'miragejs';
const { createServer } = require('miragejs');
For v0.2.x and above, createServer is an async function and must be awaited. CommonJS `require` is generally discouraged in newer projects for Mirage JS.
Model, Factory, Response
import { Model, Factory, Response } from 'miragejs';
import Model from 'miragejs/model'; // deprecated path
These core classes are imported as named exports from the top-level package. Avoid importing from internal paths as they may change.
Server
type MyServer = ReturnType<typeof createServer>;
The Server instance itself does not have a directly exported type named `Server`. Instead, infer its type from `createServer` for accurate TypeScript usage.

This quickstart demonstrates setting up a basic Mirage JS server with models, factories, seeds, and routes, then making a mock API call.

import { createServer, Model, Factory, Response } from 'miragejs'; async function setupMirage() { const server = await createServer({ environment: 'development', models: { user: Model, post: Model, }, factories: { user: Factory.extend({ name(i) { return `User ${i}`; }, email(i) { return `user${i}@example.com`; } }), post: Factory.extend({ title(i) { return `Post ${i} Title`; }, content: 'Lorem ipsum dolor sit amet.', createdAt: () => new Date() }) }, seeds(server) { let users = server.createList('user', 5); users.forEach(user => { server.createList('post', 2, { user }); }); }, routes() { this.namespace = 'api'; this.timing = 200; // Simulate network latency this.get('/users', (schema) => { return schema.users.all(); }); this.get('/users/:id', (schema, request) => { const id = request.params.id; const user = schema.users.find(id); if (!user) { return new Response(404, { 'Content-Type': 'application/json' }, { errors: ['User not found'] }); } return user; }); this.post('/posts', (schema, request) => { const attrs = JSON.parse(request.requestBody); return schema.posts.create(attrs); }); // Pass through unhandled requests this.passthrough('/some-external-api/**'); }, }); console.log('Mirage JS server initialized:', server); // Example fetch call against the mock server const response = await fetch('/api/users'); const data = await response.json(); console.log('Fetched users:', data.users); // In a real app, you would integrate this into your app's startup logic. // Don't forget to call server.shutdown() when done (e.g., in teardown). } // Call the async setup function setupMirage().catch(console.error);
Debug
Known issues
breakingStarting with v0.2.0-alpha.0, the `createServer` function is now asynchronous and must be awaited. Failing to `await` it will result in runtime errors as the server may not be fully initialized before subsequent operations.
fix
Change `const server = createServer(...)` to `const server = await createServer(...)`.
affects: >=0.2.0-alpha.0
breakingThe v0.2.x branch is an experimental alpha release and is subject to further breaking changes. It introduces significant architectural shifts, including support for MSW as an interceptor. It is not recommended for production applications until a stable release.
fix
For stable production use, remain on the v0.1.x branch. If experimenting with v0.2.x, frequently review changelogs and prepare for API adjustments.
affects: >=0.2.0-alpha.0
gotchaWhen using Mirage JS for testing, it's crucial to ensure the mock server is properly shut down after each test or test suite to prevent state leakage between tests. Forgetting `server.shutdown()` can lead to unpredictable test results.
fix
Always call `server.shutdown()` in your test teardown (e.g., `afterEach` or `afterAll` in testing frameworks) to clean up the server instance and clear intercepted requests.
affects: >=0.1.0
gotchaMirage JS intercepts network requests (XHR and Fetch). If your application code uses other methods for HTTP requests (e.g., WebSockets, EventSource, or certain native browser APIs not covered by the interceptor), Mirage JS will not mock them.
fix
Ensure all relevant network traffic goes through Fetch or XHR. If specific libraries use non-standard request methods, consider mocking those libraries directly or adjusting your application's network layer.
affects: >=0.1.0
Errors
Common errors & fixes
ReferenceError: require is not defined
Attempting to use CommonJS `require()` syntax in an ECMAScript Module (ESM) context, or in a project configured for ESM.
fix
Update your import statements to use ESM syntax: `import { createServer } from 'miragejs';`. Ensure your `package.json` has `"type": "module"` or use `.mjs` file extensions for ESM.
TypeError: Cannot read properties of undefined (reading 'namespace')
This error often occurs when trying to configure the Mirage server or define routes immediately after calling `createServer()` in v0.2.x without awaiting it, meaning `server` is still a Promise.
fix
Ensure `createServer` is `awaited`: `const server = await createServer({ ... });`.
Mirage: You called `server.create()` without passing a factory. If you're using `server.create()` to create a data record, you must also define a factory for that model.
A factory has been defined in `models` but not in `factories` for a specific model name, or there's a typo in the model name when calling `server.create()`.
fix
Verify that every model you intend to create with `server.create()` has a corresponding factory defined in the `factories` object of your server configuration with a matching key.
Mirage: Your app tried to make a XHR/Fetch request to 'http://localhost:8080/api/nonexistent-route', but there are no routes defined to handle this request. Mirage will not respond to this request.
The application made a request to an endpoint for which no route handler is defined in the Mirage JS server configuration.
fix
Add a `this.get('/api/nonexistent-route', ...)` or appropriate `this.post`/`put`/`delete` route to your `routes()` definition to handle the request. Alternatively, use `this.passthrough('/api/nonexistent-route')` if it should bypass Mirage and go to the real backend.
Upgrade
Version history
0.1.48latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
2 hits · last 30 days
node
2
Resources