chance vs faker vs json-server vs mockjs
Mocking Strategies: Data Generation vs API Simulation
chancefakerjson-servermockjsSimilar Packages:

Mocking Strategies: Data Generation vs API Simulation

chance, faker, and mockjs are libraries designed to generate mock data for testing and development, while json-server provides a full fake REST API backend. faker (the original package) is deprecated in favor of @faker-js/faker, but remains a reference point for data generation patterns. chance offers a lightweight alternative for generating random values. mockjs specializes in intercepting AJAX requests to return mock data without a real backend. json-server spins up a Node.js server that serves a JSON file as a REST API, allowing frontend teams to develop against realistic endpoints. Together, these tools cover the spectrum from generating individual fake values to simulating entire backend systems.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
chance06,5562.13 MB17710 months agoMIT
faker0-10.1 MB--MIT
json-server075,64436.9 kB70912 days agoMIT
mockjs019,656-3426 years ago-

Mocking Strategies: Data Generation vs API Simulation

When building frontend applications, you often need to simulate data or backend services before the real API is ready. The tools chance, faker, json-server, and mockjs approach this problem from different angles. Some generate raw data, while others simulate network layers. Let's break down how they work and where they fit in your architecture.

๐Ÿ—๏ธ Core Function: Data Generation vs Server Simulation

chance and faker are pure data generators.

  • They run in memory and return strings, numbers, or objects.
  • You call functions like name() or email() to get values.
  • They do not handle HTTP requests themselves.
// chance: Generate a name
const chance = new Chance();
console.log(chance.name());

// faker: Generate a name (using @faker-js/faker)
const { faker } = require('@faker-js/faker');
console.log(faker.person.fullName());

json-server is a mock API server.

  • It runs as a Node.js process on a port (e.g., 3000).
  • You send real HTTP requests (GET, POST) to it.
  • It reads a JSON file and returns data based on REST conventions.
// json-server: Start server via CLI
// npx json-server --watch db.json
// Then fetch from client:
fetch('http://localhost:3000/users/1')
  .then(res => res.json());

mockjs intercepts network requests.

  • It hooks into XMLHttpRequest or Fetch.
  • You define rules for URLs, and it returns mock data automatically.
  • Your code thinks it's talking to a real server.
// mockjs: Intercept request
Mock.mock('/api/users', 'get', {
  'list|1-10': [{ 'id|+1': 1, 'name': '@name' }]
});
// Your existing fetch call works without changes
fetch('/api/users').then(res => res.json());

๐Ÿ“ฆ Data Complexity and Customization

chance keeps things simple.

  • It has a smaller API surface.
  • Good for basic types like strings, integers, and dates.
  • Less opinionated about data structure.
// chance: Basic types
console.log(chance.integer({ min: 1, max: 100 }));
console.log(chance.date());

faker offers deep customization.

  • It covers niches like finance, medical, vehicle, and git data.
  • Supports multiple locales (e.g., en, de, zh_CN).
  • Better for realistic seeding of complex databases.
// faker: Complex domains
console.log(faker.finance.amount());
console.log(faker.vehicle.vin());
console.log(faker.git.commitMessage());

json-server relies on your JSON file.

  • It doesn't generate data dynamically by default.
  • You must populate db.json manually or via a script.
  • You can combine it with faker to seed the database.
// json-server: db.json structure
{
  "users": [
    { "id": 1, "name": "Alice" },
    { "id": 2, "name": "Bob" }
  ]
}

mockjs uses a template syntax.

  • It mixes static data with dynamic generators using symbols like |.
  • 'list|1-10' means generate a list with 1 to 10 items.
  • Powerful for defining response shapes inline.
// mockjs: Template syntax
Mock.mock({
  'data|5': [{
    'id|+1': 1,
    'email': '@email'
  }]
});

๐ŸŒ Integration: How They Connect to Your App

chance and faker are imported as modules.

  • You call them inside your test files or components.
  • No network overhead since they run locally.
  • Ideal for unit tests and storybook stories.
// chance/faker: Direct import
import { faker } from '@faker-js/faker';
const user = { name: faker.person.fullName() };

json-server requires a running process.

  • You run it separately or as an npm script.
  • Your app makes network calls to localhost.
  • Closer to production behavior (latency, headers).
# json-server: Package script
"scripts": {
  "mock:api": "json-server --watch db.json"
}

mockjs modifies the global network layer.

  • You import it once in your entry file (e.g., main.js).
  • It silently intercepts matching URLs.
  • No need to change your API service code.
// mockjs: Global setup
import './mock'; // File contains Mock.mock definitions
// Rest of app runs normally

โš ๏ธ Maintenance and Deprecation Risks

faker (original) is deprecated.

  • The original faker package is no longer maintained.
  • Security vulnerabilities will not be fixed.
  • Must use @faker-js/faker for new projects.
// โŒ Deprecated
import faker from 'faker';

// โœ… Recommended
import { faker } from '@faker-js/faker';

chance is stable but slow-moving.

  • It receives infrequent updates.
  • Safe to use but lacks modern features like tree-shaking optimizations.
  • No major deprecation warnings currently.
// chance: Stable but legacy feel
import Chance from 'chance';
const chance = new Chance();

json-server is in maintenance mode.

  • Version 0.17 is stable; version 1.0 is a complete rewrite.
  • Still widely used for prototyping.
  • Not recommended for complex logic or production.
// json-server: Check version
// npm install json-server@latest

mockjs has limited maintenance.

  • Mostly maintained by the community in China.
  • Documentation is often in Chinese.
  • TypeScript types are community-maintained and may lag.
// mockjs: Type limitations
// May require @types/mockjs which might be outdated
import * as Mock from 'mockjs';

๐Ÿ› ๏ธ Real-World Usage Patterns

Scenario 1: Unit Testing Components

You need to pass fake props to a React component.

  • โœ… Best choice: faker (or chance)
  • Why? You need in-memory data, not network requests.
// faker: Test setup
const user = { name: faker.person.fullName() };
render(<Profile user={user} />);

Scenario 2: Frontend Prototyping

You need to build the UI before the backend exists.

  • โœ… Best choice: json-server
  • Why? You can use fetch or axios exactly as you would in production.
// json-server: App code
axios.get('/api/posts').then(({ data }) => {
  // Works same as real API
});

Scenario 3: Decoupled Development

You want to mock APIs without changing backend URLs.

  • โœ… Best choice: mockjs
  • Why? It intercepts requests, so you don't need to switch base URLs.
// mockjs: Interception
Mock.mock('/api/login', { token: 'abc123' });
// Call remains: axios.post('/api/login')

Scenario 4: Seeding a Database

You need to fill a test database with 1000 records.

  • โœ… Best choice: faker
  • Why? It has the performance and variety for bulk generation.
// faker: Bulk seed
const users = Array.from({ length: 1000 }, () => ({
  name: faker.person.fullName()
}));

๐Ÿ“Š Summary: Key Differences

Featurechancefaker (original)json-servermockjs
TypeData GeneratorData GeneratorMock API ServerRequest Interceptor
ExecutionIn-memoryIn-memoryNode.js ProcessBrowser/Node Hook
NetworkNoneNoneHTTP RequestsIntercepts HTTP
MaintenanceStableโŒ DeprecatedMaintenanceCommunity/Region
Best ForSimple random valuesComplex fake dataFull REST simulationTransparent mocking

๐Ÿ’ก The Big Picture

faker (specifically @faker-js/faker) is the king of data generation. If you need realistic names, addresses, or financial data for tests, this is your tool. Avoid the original faker package entirely.

chance is a lightweight alternative for simple randomness. Use it if you want fewer dependencies and don't need faker's extensive locale support.

json-server is the standard for API prototyping. It lets you build a frontend against a real REST API structure without writing backend code. It's perfect for the "frontend-first" workflow.

mockjs solves the integration problem. It allows you to mock responses without changing your API client code. This is great for teams where switching API endpoints is difficult, but be mindful of its maintenance status.

Final Thought: In modern architectures, a common pattern is to use @faker-js/faker to seed a json-server instance. This gives you a dynamic, realistic API that regenerates data on restart, combining the strengths of both tools for the best developer experience.

How to Choose: chance vs faker vs json-server vs mockjs

  • chance:

    Choose chance if you need a lightweight, dependency-free library for generating random data in the browser or Node.js. It is well-suited for simple test data generation where bundle size matters and you don't need the extensive locale support of faker. However, be aware that its development pace is slower compared to modern alternatives.

  • faker:

    Do NOT use the original faker package in new projects as it is deprecated and unmaintained. Instead, choose its community fork @faker-js/faker if you need comprehensive, localized fake data generation with a rich API for names, addresses, finance, and more. It is the industry standard for complex data seeding in tests and demos.

  • json-server:

    Choose json-server when you need a quick, zero-code backend to prototype against. It is ideal for frontend teams waiting on API development, as it turns a JSON file into a fully functional REST API with filtering, sorting, and pagination support out of the box. It is not suitable for production logic or complex business rules.

  • mockjs:

    Choose mockjs if you are working in an environment where intercepting XMLHttpRequest or Fetch calls is preferred over running a separate server. It is popular in specific regions (like China) for decoupling frontend and backend development without changing API URLs, but be cautious of its maintenance status and lack of TypeScript support.

README for chance

Chance

Chance Logo

Build Status GitHub license GitHub stars npm jsDelivr Hits npm Coverage Status awesomeness

Chance - Random generator helper for JavaScript

Homepage: http://chancejs.com

Many more details on http://chancejs.com but this single library can generate random numbers, characters, strings, names, addresses, dice, and pretty much anything else.

It includes the basic building blocks for all these items and is built on top of a Mersenne Twister so it can generate these things with repeatability, if desired.

Usage

See the full docs for details on installation and usage.

Dependent tools

  • Chance CLI - Use Chance on the command line.
  • Chance Token Replacer - Replace tokens in a string with Chance generated items.
  • Dream.js - Lightweight json data generator
  • Fake JSON Schema - Use chance generators to populate JSON Schema samples.
  • Mocker Data Generator - Minimal JSON data generator.
  • swagger-mock-api - Generate API mocks from a Swagger spec file enriched with Chance types and constraints
  • fony - A simple command line tool for generating fake data from a template string

Or view all of the dependents on npm

Know a library that uses Chance that isn't here? Update the README and submit a PR!

Author

Victor Quinn

https://www.victorquinn.com @victorquinn

Please feel free to reach out to me if you have any questions or suggestions.

Contributors

THANK YOU!

Contribute!

Be a part of this project! You can run the test using the following.

Note: Make sure you have Yarn installed globally

  1. Install dependencies from package.json by running yarn
  2. Run the test suite via yarn test
  3. Make some fun new modules!

This project is licensed under the MIT License so feel free to hack away :)

Proudly written in Washington, D.C.