Mock API Testing with JSON Server, Faker & JS in GitHub Actions
When building modern applications, having a fast, lightweight mock API can accelerate frontend development and test automation workflows.
In this guide, youβll learn how to:
- Spin up a mock REST API server with json-server
- Auto-generate realistic fake data using @faker-js/faker
- Write and run API test automation in JavaScript using Mocha, Chai, and Axios
- Run the full pipeline in GitHub Actions CI π―
π§± Project Structure
mock-api-server/
βββ db.json
βββ generate-data.js
βββ routes.json
βββ auth-middleware.js
βββ test/
β βββ api.test.js
βββ package.json
π¦ package.json
Hereβs a minimal but powerful package.json:
{
"name": "mock-api-server",
"version": "1.0.0",
"scripts": {
"generate": "node generate-data.js",
"start": "npm run generate && json-server --watch db.json --routes routes.json --middlewares auth-middleware.js --port 3000",
"test": "mocha test/*.test.js"
},
"devDependencies": {
"json-server": "^0.17.3",
"@faker-js/faker": "^8.0.2",
"mocha": "^10.2.0",
"chai": "^4.3.7",
"axios": "^1.6.8"
}
}
Key Features:
- generate: Populates db.json with fake user data
- start: Spins up a mock API server with routing and auth middleware
- test: Runs JavaScript API tests using Mocha
π Add Basic Authorization Middleware
In auth-middleware.js:
module.exports = (req, res, next) => {
const token = req.headers['authorization'];
if (req.path.startsWith('/users') && token !== 'Bearer my-secret-token') {
return res.status(401).json({ error: 'Unauthorized' });
}
next();
};
π€ Auto-Generate Fake Data
In generate-data.js:
const fs = require('fs');
const { faker } = require('@faker-js/faker');
const generateUsers = () => {
return Array.from({ length: 10 }, (_, id) => ({
id: id + 1,
name: faker.name.fullName(),
email: faker.internet.email(),
phone: faker.phone.number()
}));
};
const data = {
users: generateUsers(),
posts: []
};
fs.writeFileSync('db.json', JSON.stringify(data, null, 2));
π§ͺ JavaScript Test:
test/api.test.js
const axios = require('axios');
const { expect } = require('chai');
const BASE_URL = 'http://localhost:3000';
const HEADERS = {
Authorization: 'Bearer my-secret-token'
};
describe('Mock API Server Tests', () => {
it('GET /users should return an array', async () => {
const res = await axios.get(`${BASE_URL}/users`, { headers: HEADERS });
expect(res.status).to.equal(200);
expect(res.data).to.be.an('array');
});
it('POST /users should create a user', async () => {
const res = await axios.post(`${BASE_URL}/users`, {
name: 'Test User',
email: 'test@example.com'
}, { headers: HEADERS });
expect(res.status).to.equal(201);
});
it('PUT /users/1 should update a user', async () => {
const res = await axios.put(`${BASE_URL}/users/1`, {
name: 'Updated User',
email: 'updated@example.com'
}, { headers: HEADERS });
expect(res.status).to.equal(200);
});
it('DELETE /users/1 should delete a user', async () => {
const res = await axios.delete(`${BASE_URL}/users/1`, { headers: HEADERS });
expect(res.status).to.equal(200);
});
});
π GitHub Actions:
.github/workflows/test.yml
Hereβs how you automate all of this in CI:
name: Mock API Server Tests
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
- name: Install dependencies
run: npm install
- name: Start mock API server in background
run: |
npm start &
sleep 5 # Wait for the server to be ready
- name: Generate Data for the tests
run: npm run generate
- name: Run JS API tests
run: npm run test
π― Collection for all the APIs to use on Postman
### GET all users
curl --location 'http://localhost:3000/users' \
--header 'Authorization: Bearer my-secret-token'
### GET user by ID
curl --location 'http://localhost:3000/users/1' \
--header 'Authorization: Bearer my-secret-token'
### POST create new user
curl --location 'http://localhost:3000/users' \
--header 'Authorization: Bearer my-secret-token' \
--header 'Content-Type: application/json' \
--data '{
"name": "Charlie",
"email": "charlie@example.com"
}'
### PUT update user
curl --location --request PUT 'http://localhost:3000/users/1' \
--header 'Authorization: Bearer my-secret-token' \
--header 'Content-Type: application/json' \
--data '{
"name": "Charlie Updated",
"email": "charlie.updated@example.com"
}'
### DELETE user
curl --location --request DELETE 'http://localhost:3000/users/1' \
--header 'Authorization: Bearer my-secret-token'
π― Final Thoughts
With just a few files and no real backend, youβve created:
- A realistic mock API server
- Fake user data using faker
- A secure endpoint with token-based auth
- Automated JavaScript tests
- CI pipeline on GitHub Actions
This setup is perfect for frontend mocks, test automation bootstraps, and sandbox environments.
I have created a project on GitHub Actions and added the code here. Also, I have added the pipeline link to view the results here.
Feel free to hit clap if you like the content. Happy Automation Testing :) Cheers. π
If you guys want to support my work, then leave me a good rating for my Chrome plugin here and Firefox plugin here.