What is miragejs?
MirageJS is a client-side server to help you build, test, and share your JavaScript application. It allows you to mock APIs and create a simulated backend environment, which can be very useful for frontend development and testing.
What are miragejs's main functionalities?
Mocking API Endpoints
MirageJS allows you to mock API endpoints easily. In this example, a GET request to '/api/users' returns a list of users.
const { createServer } = require('miragejs');
createServer({
routes() {
this.get('/api/users', () => {
return {
users: [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
]
};
});
}
});
Defining Models and Factories
MirageJS allows you to define models and factories to generate mock data. This example creates a 'user' model and a factory to generate 10 users with names 'User 1' to 'User 10'.
const { createServer, Model, Factory } = require('miragejs');
createServer({
models: {
user: Model
},
factories: {
user: Factory.extend({
name(i) {
return `User ${i + 1}`;
}
})
},
seeds(server) {
server.createList('user', 10);
},
routes() {
this.get('/api/users', (schema) => {
return schema.users.all();
});
}
});
Handling Relationships
MirageJS supports defining relationships between models. In this example, a 'user' has many 'posts' and a 'post' belongs to a 'user'.
const { createServer, Model, hasMany, belongsTo } = require('miragejs');
createServer({
models: {
user: Model.extend({
posts: hasMany()
}),
post: Model.extend({
user: belongsTo()
})
},
seeds(server) {
let user = server.create('user', { name: 'Alice' });
server.create('post', { title: 'Post 1', user });
server.create('post', { title: 'Post 2', user });
},
routes() {
this.get('/api/users', (schema) => {
return schema.users.all();
});
this.get('/api/posts', (schema) => {
return schema.posts.all();
});
}
});
Other packages similar to miragejs
json-server
json-server is a package that allows you to create a full fake REST API with zero coding in less than 30 seconds. It is simpler and more lightweight compared to MirageJS, but it lacks the advanced features like model relationships and factories.
msw
msw (Mock Service Worker) is a library for mocking network requests in browser and Node.js. It intercepts requests on the network level and provides more flexibility in terms of request handling. However, it does not provide built-in support for models and factories like MirageJS.
nock
nock is an HTTP mocking and expectations library for Node.js. It is primarily used for testing Node.js applications by intercepting HTTP requests and providing mock responses. Unlike MirageJS, it is not designed for client-side applications.
Mirage JS
A client-side server to develop, test and prototype your JavaScript app.
Documentation
Visit miragejs.com to read the docs.