Skip to content

Commit

Permalink
Merge pull request #128 from Code-Hammers/CHE-162/task/Add-Prettier-C…
Browse files Browse the repository at this point in the history
…onfig-And-Linting

[CHE-162] Add Prettier Config and Linting
  • Loading branch information
brok3turtl3 authored Jun 5, 2024
2 parents adaa0ba + 3950dac commit 75db4bd
Show file tree
Hide file tree
Showing 112 changed files with 7,106 additions and 2,608 deletions.
9 changes: 4 additions & 5 deletions .github/workflows/build-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,12 @@ jobs:
steps:
- uses: actions/checkout@v3
- name: Build Docker Image
run: docker build -t codehammers/cd-testv1:latest -f Dockerfile-dev .
run: docker build -t codehammers/ch-dev-dep-v2:latest -f Dockerfile-dev .
- name: Install Root Dependencies
run: docker run codehammers/cd-testv1:latest npm install
run: docker run codehammers/ch-dev-dep-v2:latest npm install
- name: Install Client Dependencies
run: docker run codehammers/cd-testv1:latest /bin/sh -c "cd client && npm install"
#- name: List node_modules
#run: docker run codehammers/cd-testv1:latest /bin/sh -c "ls node_modules && cd client && ls node_modules"
run: docker run codehammers/ch-dev-dep-v2:latest /bin/sh -c "cd client && npm install"
- run: LINT_COMMAND=lint docker-compose -f docker-compose-lint.yml up --abort-on-container-exit
- run: docker-compose -f docker-compose-test.yml up --abort-on-container-exit
env:
JWT_SECRET: ${{ secrets.JWT_SECRET }}
9 changes: 9 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# These files should always be ignored by Prettier.

build/
coverage/
dist/
node_modules/
package-lock.json
*.test.jsx.snap
*.test.tsx.snap
8 changes: 8 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"semi": true,
"singleQuote": true,
"jsxSingleQuote": false,
"printWidth": 100,
"tabWidth": 2,
"trailingComma": "all"
}
8 changes: 8 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,

"editor.codeActionsOnSave": {
"source.fixAll.eslint": "always"
}
}
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Set Node.js version
FROM node:18.17.1 as builder
FROM node:20.14.0 as builder

# Set the working directory
WORKDIR /usr/src/app
Expand All @@ -22,7 +22,7 @@ RUN cd client && npm run build
RUN npm run build

# Set up the final image
FROM node:18.17.1
FROM node:20.14.0

# Set the working directory
WORKDIR /usr/src/app
Expand Down
2 changes: 1 addition & 1 deletion Dockerfile-dev
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Set Node version
FROM node:18.17.1
FROM node:20.14.0

# Install webpack globally
RUN npm install webpack -g
Expand Down
38 changes: 17 additions & 21 deletions __tests__/db.test.ts
Original file line number Diff line number Diff line change
@@ -1,56 +1,52 @@
import mongoose from "mongoose";
import connectDB from "../server/config/db";
import mongoose from 'mongoose';
import connectDB from '../server/config/db';

jest.mock("mongoose", () => ({
jest.mock('mongoose', () => ({
connect: jest.fn().mockImplementation(() =>
Promise.resolve({
connection: { host: "test-host" },
})
connection: { host: 'test-host' },
}),
),
}));

describe("connectDB", () => {
describe('connectDB', () => {
let mockExit: jest.SpyInstance;
let mockConsoleError: jest.SpyInstance;
let mockConsoleLog: jest.SpyInstance;

beforeEach(() => {
mockExit = jest
.spyOn(process, "exit")
.mockImplementation((_code) => undefined as never);
mockConsoleError = jest.spyOn(console, "error").mockImplementation();
mockConsoleLog = jest.spyOn(console, "log").mockImplementation();
mockExit = jest.spyOn(process, 'exit').mockImplementation((_code) => undefined as never);
mockConsoleError = jest.spyOn(console, 'error').mockImplementation();
});

afterEach(() => {
jest.clearAllMocks();
});

it("should call mongoose.connect with MONGO_URI", async () => {
process.env.MONGO_URI = "test-mongo-uri";
it('should call mongoose.connect with MONGO_URI', async () => {
process.env.MONGO_URI = 'test-mongo-uri';
await connectDB();
expect(mongoose.connect).toHaveBeenCalledWith("test-mongo-uri");
expect(mongoose.connect).toHaveBeenCalledWith('test-mongo-uri');
});

it("should log an error and exit the process if mongoose.connect fails", async () => {
process.env.MONGO_URI = "test-mongo-uri";
it('should log an error and exit the process if mongoose.connect fails', async () => {
process.env.MONGO_URI = 'test-mongo-uri';
(mongoose.connect as jest.Mock).mockImplementationOnce(() => {
throw new Error("test error");
throw new Error('test error');
});

await connectDB();

expect(mockConsoleError).toHaveBeenCalledWith("test error");
expect(mockConsoleError).toHaveBeenCalledWith('test error');
expect(mockExit).toHaveBeenCalledWith(1);
});

it("should throw an error if MONGO_URI is not defined", async () => {
it('should throw an error if MONGO_URI is not defined', async () => {
delete process.env.MONGO_URI;

await connectDB();

expect(mockConsoleError).toHaveBeenCalledWith(
"MONGO_URI must be defined in the environment variables."
'MONGO_URI must be defined in the environment variables.',
);
expect(mockExit).toHaveBeenCalledWith(1);
});
Expand Down
25 changes: 10 additions & 15 deletions __tests__/errorController.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Request, Response, NextFunction } from "express";
import { notFound, errorHandler } from "../server/controllers/errorControllers";
import { Request, Response, NextFunction } from 'express';
import { notFound, errorHandler } from '../server/controllers/errorControllers';

describe("Middleware Tests", () => {
describe('Middleware Tests', () => {
let mockRequest: Partial<Request>;
let mockResponse: Partial<Response>;
let mockNext: NextFunction;
Expand All @@ -15,29 +15,24 @@ describe("Middleware Tests", () => {
mockNext = jest.fn();
});

describe("notFound Middleware", () => {
it("should return 404 and the original URL", () => {
describe('notFound Middleware', () => {
it('should return 404 and the original URL', () => {
notFound(mockRequest as Request, mockResponse as Response, mockNext);
expect(mockResponse.status).toHaveBeenCalledWith(404);
expect(mockNext).toHaveBeenCalled();
});
});

describe("errorHandler Middleware", () => {
it("should handle the error correctly", () => {
const mockError = new Error("Some error");
errorHandler(
mockError,
mockRequest as Request,
mockResponse as Response,
mockNext
);
describe('errorHandler Middleware', () => {
it('should handle the error correctly', () => {
const mockError = new Error('Some error');
errorHandler(mockError, mockRequest as Request, mockResponse as Response, mockNext);
expect(mockResponse.status).toHaveBeenCalledWith(400);
expect(mockResponse.json).toHaveBeenCalledWith(
expect.objectContaining({
message: expect.anything(),
stack: expect.any(String),
})
}),
);
});
});
Expand Down
50 changes: 25 additions & 25 deletions __tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import request from "supertest";
import app, { startServer } from "../server/index";
import { Server } from "http";
import request from 'supertest';
import app, { startServer } from '../server/index';
import { Server } from 'http';
import mongoose from 'mongoose';

let server: Server;
// TODO
/*eslint jest/no-disabled-tests: "off"*/

import mongoose from "mongoose";
let server: Server;

beforeEach(() => {
server = startServer();
Expand All @@ -24,49 +26,47 @@ afterAll(async () => {
await mongoose.connection.close();
});

describe("API Endpoints", () => {
xit("should get the API Running message in development", async () => {
const res = await request(app).get("/api");
describe('API Endpoints', () => {
xit('should get the API Running message in development', async () => {
const res = await request(app).get('/api');
expect(res.statusCode).toEqual(200);
expect(res.body).toHaveProperty("message", "API Running - Hazzah!");
expect(res.body).toHaveProperty('message', 'API Running - Hazzah!');
});

xit("should serve the frontend files in production", async () => {
process.env.NODE_ENV = "production";
xit('should serve the frontend files in production', async () => {
process.env.NODE_ENV = 'production';

const res = await request(app).get("/");
const res = await request(app).get('/');
expect(res.statusCode).toEqual(200);

expect(res.headers["content-type"]).toContain("text/html");
expect(res.headers['content-type']).toContain('text/html');
});

xit("should catch all routes and serve the frontend in production", async () => {
process.env.NODE_ENV = "production";
const res = await request(app).get("/nonexistentroute");
xit('should catch all routes and serve the frontend in production', async () => {
process.env.NODE_ENV = 'production';
const res = await request(app).get('/nonexistentroute');
expect(res.statusCode).toEqual(200);
expect(res.headers["content-type"]).toContain("text/html");
expect(res.headers['content-type']).toContain('text/html');
});
});

describe("Server Start-Up", () => {
it("should start up the server if required as main module", async () => {
describe('Server Start-Up', () => {
it('should start up the server if required as main module', async () => {
const originalLog = console.log;
const logCalls: string[] = [];
console.log = jest.fn((...args: any[]) => {
logCalls.push(args.join(" "));
console.log = jest.fn((...args: string[]) => {
logCalls.push(args.join(' '));
});

jest.resetModules();

await new Promise((resolve) => {
if (server) {
server.on("listening", resolve);
server.on('listening', resolve);
}
});

const hasExpectedLog = logCalls.some((log) =>
log.includes("Server running in")
);
const hasExpectedLog = logCalls.some((log) => log.includes('Server running in'));
expect(hasExpectedLog).toBe(true);

console.log = originalLog;
Expand Down
Loading

0 comments on commit 75db4bd

Please sign in to comment.