| 1 | import test from "ava";
|
| 2 | import { PrismaClient } from '@prisma/client';
|
| 3 | import { PrismaPg } from '@prisma/adapter-pg';
|
| 4 | import request from 'supertest';
|
| 5 | import bcrypt from 'bcryptjs';
|
| 6 | import 'dotenv/config';
|
| 7 | import { Express } from 'express';
|
| 8 | import { createApp } from '../../src/createApp';
|
| 9 |
|
| 10 | let prisma: PrismaClient;
|
| 11 | let app: Express;
|
| 12 |
|
| 13 | test.before(() => {
|
| 14 | process.env.NODE_ENV = 'test';
|
| 15 |
|
| 16 | const connectionString = process.env.DATABASE_URL || 'postgres://user:password@orbit_db:5432/orbit_test';
|
| 17 | const adapter = new PrismaPg({ connectionString });
|
| 18 | prisma = new PrismaClient({ adapter });
|
| 19 |
|
| 20 | // Create Express app with test Prisma client
|
| 21 | app = createApp(prisma);
|
| 22 | });
|
| 23 |
|
| 24 | test.beforeEach(async () => {
|
| 25 | // Clean database before each test
|
| 26 | try {
|
| 27 | await prisma.user.deleteMany({});
|
| 28 | } catch (err) {
|
| 29 | console.error('Error cleaning test DB:', err);
|
| 30 | }
|
| 31 | });
|
| 32 |
|
| 33 | test.after.always(async () => {
|
| 34 | await prisma?.$disconnect();
|
| 35 | });
|
| 36 |
|
| 37 | test("PUT /users/:id updates user profile", async (t) => {
|
| 38 | // Create a user first
|
| 39 | const user = await prisma.user.create({
|
| 40 | data: {
|
| 41 | email: "update@example.com",
|
| 42 | firstName: "Original",
|
| 43 | lastName: "Name",
|
| 44 | encryptedPassword: bcrypt.hashSync("password", 10)
|
| 45 | }
|
| 46 | });
|
| 47 |
|
| 48 | const updateData = {
|
| 49 | firstName: "Updated",
|
| 50 | lastName: "Profile"
|
| 51 | };
|
| 52 |
|
| 53 | // TODO: Gotta check why its failing. Most likely due to the
|
| 54 | // cors/credentials: true line
|
| 55 | const response = await request(app)
|
| 56 | .put(`/users/${user.id}`)
|
| 57 | .send(updateData)
|
| 58 | .expect('Content-Type', /json/)
|
| 59 | .expect(200);
|
| 60 |
|
| 61 | t.is(response.body.user.firstName, updateData.firstName);
|
| 62 | t.is(response.body.user.lastName, updateData.lastName);
|
| 63 | t.is(response.body.user.email, user.email); // Should remain unchanged
|
| 64 |
|
| 65 | // Verify in database
|
| 66 | const dbUser = await prisma.user.findUnique({
|
| 67 | where: { id: user.id }
|
| 68 | });
|
| 69 |
|
| 70 | t.is(dbUser!.firstName, updateData.firstName);
|
| 71 | t.is(dbUser!.lastName, updateData.lastName);
|
| 72 | });
|
| 73 |
|
| 74 | test("PUT /users/:id returns 404 for non-existent user", async (t) => {
|
| 75 | const response = await request(app)
|
| 76 | .put('/users/999999')
|
| 77 | .send({
|
| 78 | firstName: "Updated",
|
| 79 | lastName: "Name"
|
| 80 | })
|
| 81 | .expect('Content-Type', /json/)
|
| 82 | .expect(404);
|
| 83 |
|
| 84 | t.truthy(response.body.error);
|
| 85 | });
|