Mocha chai unit test cases for authenticated end point

 

This example will show how to write unit test cases in node js for an authenticated end point.

process.env.NODE_ENV = "test";

const chai = require("chai");
const chaiHttp = require("chai-http");
const { faker } = require('@faker-js/faker');
const Server = require("../src/server.js");


chai.use(chaiHttp);
const {expect} = chai;
const should = chai.should();

let token;
let app;

describe('Users route', () => {
  const signin = '/auth/login';
  const users='/api/users';
  const preSave = {
    username: 'superadmin', // TODO from config
    password: '123',
  };
  // create user for each role //
  const userCreate=[{data:{
    email: faker.internet.email(),
    full_name: faker.name.findName(),
    groups: [],
    password: faker.internet.password(),
    passwordVerify: "",
    roles: "msp",
    userStatus: true,
    username: faker.name.firstName()}},{data:{
    email: faker.internet.email(),
    full_name: faker.name.findName(),
    groups: [],
    password: faker.internet.password(),
    passwordVerify: "",
    roles: "administrator",
    userStatus: true,
    username: faker.name.firstName()}},{data:{
    email: faker.internet.email(),
    full_name: faker.name.findName(),
    groups: [],
    password: faker.internet.password(),
    passwordVerify: "",
    roles: "user",
    userStatus: true,
    username: faker.name.firstName()}}];
  
  // TODO testdatabase
  before(async () => {
    const server = await Server();
    app = server?.app;
    const result = await chai
      .request(app)
      .post(signin)
      .send(preSave);
      expect(result.status).to.equal(200);
      token = result.body.accessToken;
  });

  // TODO after all test have run we drop our test database
  after('droping test db', async () => {
   // console.log("done.");
    // process.exit(0);
  });
  // List users
  describe('/GET List Users', () => {
    it('should return status 200', async () => {
      try {
        const result = await chai
          .request(app)
          .get(users)
          .set('Authorization',`Bearer ${token}`);
        expect(result.status).to.equal(200);
      } catch (error) {
        throw new Error(error);
      }
    });
  });

  // Create user for each role
  userCreate.forEach((run) => {
    describe(`/PUT Create user ${ run.data.username} for role ${ run.data.roles}`, () => {
      it('should create new user if not exists', async () => {
        try {
          const result = await chai
            .request(app)
            .put(users)
            .set('Authorization',`Bearer ${token}`)
            .send(run);
          expect(result.status).to.equal(200)
        } catch (error) {
          throw new Error(error);
        }
      });
      it(`should return 403 if user was found user ${ run.data.username} for role ${ run.data.roles}`, async () => {
        try {
          const result =  await chai
            .request(app)
            .put(users)
            .set('Authorization',`Bearer ${token}`)
            .send(run);
          expect(result.status).to.equal(403);
        } catch (error) {
          throw new Error(error);
        }
      });
    });
  });

  // Update user full-name, email, password, enable/disable
  describe('/GET Update Users', () => {
    it('should return status 200', async () => {
      try 
      {
        const result = await chai
          .request(app)
          .get(users)
          .set('Authorization',`Bearer ${token}`);
        expect(result.status).to.equal(200);
        const existingusers= [result.body.data[0]];
        // Update existing user
        existingusers.forEach((run) => {
          describe(`/PUT Updating user ${ run.profile.first_name} ${ run.profile.last_name}`, () => {
            it('should update user if exists', async () => {
              try {
                const resultUpdate = await chai
                  .request(app)
                  .post(`${users}/${run.id}`)
                  .set('Authorization',`Bearer ${token}`)
                  .send({
                    data:{ 
                    email: faker.internet.email(),
                    full_name: faker.name.findName(),
                    password: faker.internet.password(),
                    userStatus: true
                  }});
                expect(resultUpdate.status).to.equal(200)
              } catch (error) {
                throw new Error(error);
              }
            });
          });
        });
      } catch (error) {
        throw new Error(error);
      }
    });
  });

});