/** * @file user.integration.test.ts * * @description * Integration tests for…
- User
/**
- @file user.integration.test.ts
- @description
- Integration tests for user-related API endpoints.
- Validates full stack including authentication, route correctness,
- privacy filtering, and file upload.
- Includes request logging middleware added to app for debugging. */
import request from 'supertest'; import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import express from 'express'; import path from 'path'; import fs from 'fs'; import prisma from '../src/prismaClient.js'; import { seedAll } from '../prisma/seedAll'; import { generateTestToken } from './utils/testUtils'; import app from '../src/app'; // Use actual app import
// Add request logging middleware for debugging unmatched routes and requests app.use((req, res, next) => { console.log(
[TEST LOG] Incoming request: ${req.method} ${req.originalUrl}); next(); });const seededCountyLive = '7378d182-26c6-45c1-864e-dee1ed8a3ffd'; const seededConstituencyLive = '524de848-f940-406d-894d-df8c6bee6fa8'; const seededCountyOrigin = '80ed8e1d-db92-409b-b004-2c3099ef094d'; const seededConstituencyOrigin = 'c12317c3-cb0a-4a3b-ba8c-2f288b012858'; const seededIndustryId = '20e7b855-4de8-46b3-8000-c01c8f28ac0c'; const seededGoodsServices = [ '0168c1b6-8957-4fc7-b25f-0d2ea8bba623', '7ebfa3cf-5459-454a-9765-67a44f7f85f9', ];
// Ensure upload directory exists before tests const uploadDir = path.join(process.cwd(), 'uploads', 'avatars'); if (!fs.existsSync(uploadDir)) { fs.mkdirSync(uploadDir, { recursive: true }); }
describe('User API Integration Tests', () => { let userId: string; let jwtToken: string; const testWallet = '0xf1eae4a2011695ab127f73b7e910c45ca4b30e5a'; const testEmail =
integrationtest_${Date.now()}@example.com;beforeAll(async () => { await prisma.$connect(); await seedAll();
// Create a user to test against via API const res = await request(app) .post('/api/users') .send({ walletAddress: testWallet, email: testEmail, name: 'Integration Test User', phoneNumber: '0712345678', constituencyOrigin: seededConstituencyOrigin, countyOrigin: seededCountyOrigin, constituencyLive: seededConstituencyLive, countyLive: seededCountyLive, industry: seededIndustryId, goodsServices: seededGoodsServices, avatarUrl: 'https://example.com/avatar.png', }); expect(res.status).toBe(201); userId = res.body.id; jwtToken = generateTestToken(userId, testWallet, ['system:general_user']);});
afterAll(async () => { await prisma.$disconnect(); });
it('should retrieve the current user profile', async () => { const res = await request(app) .get('/api/users/me') .set('Authorization',
Bearer ${jwtToken});expect(res.status).toBe(200); expect(res.body).toHaveProperty('id', userId); expect(res.body.email).toBe(testEmail); - Assistant
- User
❯ tests/user.integration.test.ts (5 tests | 4 failed) 2473ms × User API Integration Tests > should retrieve the current user profile 48ms → expected 404 to be 200 // Object.is equality × User API Integration Tests > should update the current user profile 16ms → expected 404 to be 200 // Object.is equality ✓ User API Integration Tests > should reject access without auth token 8ms × User API Integration Tests > should upload avatar successfully 30ms → expected 404 to be 200 // Object.is equality × User API Integration Tests > should fetch user by wallet address 11ms → expected 404 to be 200 // Object.is equality
- Assistant
- User
help me understand, who is the current user? shouldnt our integration file run the whole thing from even creating the user/
- Assistant
- User
/**
- @file user.routes.ts
- @description
- Defines all Express routes pertaining to user operations including:
-
- User registration and public lookups
-
- Protected profile retrieval, updates, and avatar uploads
-
- Middleware integration for authentication and RBAC authorization */
import express from 'express'; import * as userController from '../controllers/user.controller.js'; import { authMiddleware } from '../middlewares/auth.middleware.js'; import { attachUserRoles } from '../middlewares/attachUserRoles.middleware.js'; import { authorize } from '../middlewares/rbac.middleware.js'; import { createUploader } from '../middlewares/upload.middleware.js'; import { USER_ACCESS_ROLES } from '../constants/roles.js';
- Assistant
- User
but is the user authenticated because i see thats the only test that passed, it means they are not authenticated right?
- Assistant
- User
in user.routes i see router.get('/me',
but our test file has /api/me...is that accurate
- Assistant
- User
can we debug where the problem is exactly?
- Assistant
- User
- Assistant
- User
FAIL tests/user.integration.test.ts [ tests/user.integration.test.ts ] TypeError: Cannot read properties of undefined (reading 'stack') ❯ tests/user.integration.test.ts:22:13 20| 21| console.log('Registered user routes:'); 22| app._router.stack.forEach(layer => { | ^ 23| if (layer.route && layer.route.path.startsWith('/me')) { 24| console.log(layer.route.path);
- Assistant
The error means that is , so trying to access fails.
- User
wait, should our test file import the routes files?
- Assistant
Good question!
Usually, no, your test file should not import route files directly—it should import the fully configured Express app instance, which itself imports and mounts all the routes.
Why?
- Your
app.tsalready imports and mounts all route files (user.routes.tsetc.). - Tests run against the
appinstance exported byapp.ts. - Test files should only interact with the app via HTTP requests (e.g.
supertest(request(app))).
- Your
- User
where is the 404 coming from. add logger details so we can know
- Assistant