SuperTest Framework Setup Guide

Step 1: Install Node.js

Ensure Node.js is installed by running:

node -v
npm -v

If not installed, download from Node.js Official Website.

Step 2: Create a New Project

mkdir supertest-api-project
cd supertest-api-project
npm init -y

Step 3: Install Dependencies

npm install supertest mocha chai --save-dev
npm install mochawesome --save-dev

Step 4: Create Project Structure

/supertest-api-project
 ├── /test
 │   └── sampleTest.js
 ├── /utils
 │   └── config.js
 ├── .mocharc.json
 ├── package.json
 └── README.md

Step 5: Configure Mocha

{
  "require": ["chai/register-assert", "chai/register-expect", "chai/register-should"],
  "reporter": "mochawesome",
  "timeout": 5000
}

Step 6: Write Your First Test

const request = require('supertest');
const baseURL = 'https://jsonplaceholder.typicode.com';

describe('GET /posts', () => {
    it('should return all posts', async () => {
        const response = await request(baseURL).get('/posts');
        expect(response.status).to.equal(200);
        expect(response.body).to.be.an('array');
    });

    it('should return a specific post', async () => {
        const response = await request(baseURL).get('/posts/1');
        expect(response.status).to.equal(200);
        expect(response.body.id).to.equal(1);
    });
});

Step 7: Add Script in package.json

"scripts": {
  "test": "mocha ./test --recursive"
}

Step 8: Run Your Tests

npm test

Step 9: View Test Reports (Optional)

For Mochawesome reports, the results will be available in the /mochawesome-report folder.

Step 10: Additional Tips

  • âś… Use .env files for environment variables.
  • âś… Utilize before() and after() hooks in Mocha for setup/teardown logic.
  • âś… Consider adding ESLint for clean and consistent code.
Next Post Previous Post
No Comment
Add Comment
comment url