Agromind-backend / backend /tests /validateToken.test.js
gh-action-hf-auto
auto: sync backend from github@32fb9685
8a6248c
import jwt from 'jsonwebtoken';
// Import the route file to test the validateToken handler directly
// We'll extract it by creating mock req/res objects like auth.test.js does
const JWT_KEY = 'test-jwt-secret-key-for-testing';
beforeAll(() => {
process.env.JWT_KEY = JWT_KEY;
});
// Dynamically import the module after env is set
let validateTokenModule;
beforeAll(async () => {
validateTokenModule = await import('../routes/validateTokenRoutes.js');
});
const createMockResponse = () => {
const res = {};
res.status = (code) => {
res.statusCode = code;
return res;
};
res.json = (data) => {
res.jsonData = data;
return res;
};
return res;
};
describe('Validate Token Route', () => {
// We need to test the handler directly. Since the router exports are GET routes,
// we'll simulate by calling the route handler via a test Express app.
let app;
let request;
beforeAll(async () => {
const express = (await import('express')).default;
const cookieParser = (await import('cookie-parser')).default;
const supertest = (await import('supertest')).default;
app = express();
app.use(cookieParser());
app.use('/api/auth', validateTokenModule.default);
request = supertest(app);
});
test('should return 401 when no token is provided', async () => {
const response = await request.get('/api/auth/validate-token');
expect(response.status).toBe(401);
expect(response.body).toEqual({ message: 'No token found' });
});
test('should validate token from cookie', async () => {
const token = jwt.sign({ id: 'user123', role: 'farmer' }, JWT_KEY, { expiresIn: '1h' });
const response = await request
.get('/api/auth/validate-token')
.set('Cookie', `token=${token}`);
expect(response.status).toBe(200);
expect(response.body).toMatchObject({ userId: 'user123', role: 'farmer' });
});
test('should validate token from Authorization Bearer header', async () => {
const token = jwt.sign({ id: 'user456', role: 'expert' }, JWT_KEY, { expiresIn: '1h' });
const response = await request
.get('/api/auth/validate-token')
.set('Authorization', `Bearer ${token}`);
expect(response.status).toBe(200);
expect(response.body).toMatchObject({ userId: 'user456', role: 'expert' });
});
test('should return 401 for invalid token', async () => {
const response = await request
.get('/api/auth/validate-token')
.set('Authorization', 'Bearer invalid-token-here');
expect(response.status).toBe(401);
expect(response.body).toEqual({ message: 'Invalid token' });
});
test('should return 401 for expired token', async () => {
const token = jwt.sign({ id: 'user789', role: 'farmer' }, JWT_KEY, { expiresIn: '0s' });
// Wait a moment for the token to expire
await new Promise(resolve => setTimeout(resolve, 1000));
const response = await request
.get('/api/auth/validate-token')
.set('Cookie', `token=${token}`);
expect(response.status).toBe(401);
expect(response.body).toEqual({ message: 'Invalid token' });
});
test('should prefer cookie token over Authorization header', async () => {
const cookieToken = jwt.sign({ id: 'cookie-user', role: 'farmer' }, JWT_KEY, { expiresIn: '1h' });
const headerToken = jwt.sign({ id: 'header-user', role: 'expert' }, JWT_KEY, { expiresIn: '1h' });
const response = await request
.get('/api/auth/validate-token')
.set('Cookie', `token=${cookieToken}`)
.set('Authorization', `Bearer ${headerToken}`);
expect(response.status).toBe(200);
expect(response.body).toMatchObject({ userId: 'cookie-user', role: 'farmer' });
});
});