File size: 3,965 Bytes
8a6248c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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' });
    });
});