This project provides a template for testing REST APIs using Mocha, SuperTest, and related tools. It is designed for easy setup and quick test execution, even after a long break from the project.
Note: This project is compatible with Node.js
v22.14.0and uses the latest supported versions of all dependencies as of December 2025.
-
Clone the repository (if you haven't already):
git clone <your-repo-url> cd mocha-api-testing
-
Install dependencies:
npm install
-
Configure environment variables:
- Create a
.envfile in the project root (see Environment Variables).
- Create a
-
Run tests:
npm test -
Generate a test report:
npm run test-report
This project uses a .env file to store sensitive information and configuration. Example:
BASE_URL=https://gorest.co.in/public/v2/
TOKEN=your_api_token_hereBASE_URL: The base URL for the API under test (e.g., Go REST API).TOKEN: Your personal access token for authentication. Obtain this by logging in at Go REST API and copying your access token from your account.
Never commit your .env file to version control.
config/– Configuration files (e.g., request setup, token management)helpers/– Helper functions for API callstest/– Mocha test files.env– Environment variables (not committed).mocharc.yaml– Mocha configuration (uses Babel for ES6+ support)
npm test– Runs all tests with Mochanpm run test-report– Runs tests and generates a Mochawesome HTML report
Below are the main packages used in this project, with a brief description of why each is included:
- mocha: Test runner for JavaScript, used to structure and run tests.
- chai: Assertion library for writing readable test assertions.
- supertest: HTTP assertions for testing REST APIs, works well with Mocha.
- @babel/core: Babel compiler core.
- @babel/cli: Command-line interface for Babel.
- @babel/node: Run Node.js scripts with Babel transpilation.
- @babel/register: Hook to compile files on the fly when required.
- @babel/preset-env: Smart preset to compile ES6+ down to ES5.
- dotenv: Loads environment variables from
.envintoprocess.env. - @faker-js/faker: Generates fake data for testing (e.g., random names, emails).
- mochawesome: Generates beautiful HTML/CSS test reports for Mocha.
To generate random data in your tests, use Faker:
import { faker } from '@faker-js/faker';
const randomName = faker.person.fullName();To generate a Mochawesome report:
npm run test-reportThe report will be saved in the mochawesome-report/ directory.
- If you encounter issues after upgrading dependencies, check the official documentation and release notes for breaking changes.
- Ensure your Node.js version is at least v22.14.0 for best compatibility.