Integration test with authentication - mocha

PHOTO EMBED

Sun Mar 12 2023 09:27:05 GMT+0000 (Coordinated Universal Time)

Saved by @mtommasi

const request = require('supertest');
const app = require('../app');
const expect = require('chai').expect;

describe('Protected Route', () => {
  let token;

  before((done) => {
    // Authenticate test user and retrieve JWT token
    request(app)
      .post('/auth/login')
      .send({
        username: 'testuser',
        password: 'password'
      })
      .end((err, res) => {
        token = res.body.token; // store JWT token for future requests
        done();
      });
  });

  it('should return a 200 status code when accessing protected route with valid token', (done) => {
    // Make request to protected route with valid JWT token
    request(app)
      .get('/protected')
      .set('Authorization', `Bearer ${token}`)
      .expect(200)
      .end((err, res) => {
        if (err) return done(err);
        expect(res.body).to.have.property('message').that.equals('You are authorized to access this resource.');
        done();
      });
  });
});
content_copyCOPY