Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,6 @@ typings/
.elasticbeanstalk/*
!.elasticbeanstalk/*.cfg.yml
!.elasticbeanstalk/*.global.yml

# Test Coverage
coverage
18 changes: 15 additions & 3 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,19 @@
/** @type {import('ts-jest').JestConfigWithTsJest} **/
export default {
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
testEnvironment: 'node',
transform: {
'^.+\.tsx?$': ['ts-jest', {}],
'^.+\\.tsx?$': ['ts-jest', {}],
},
coverageDirectory: 'coverage',
collectCoverage: true,
collectCoverageFrom: [
'src/**/*.{ts,tsx}',
'!src/**/*.d.ts',
'!src/**/*.test.{ts,tsx}',
'!src/**/index.ts',
'!src/**/types.ts',
],
coverageReporters: ['text', 'lcov'],
testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/dist/'],
modulePathIgnorePatterns: ['<rootDir>/dist/'],
};
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@
"description": "",
"main": "./src/index.ts",
"private": true,
"type": "module",
"scripts": {
"prebuild": "rm -rf dist",
"build": "tsc",
"start": "node dist/index.js",
"dev": "env-cmd ts-node src/index.ts",
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"lint": "eslint . --ext .ts",
"lint:fix": "eslint . --ext .ts --fix",
"lint:check": "eslint . --ext .ts --no-ignore",
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import 'dotenv/config';
import request, { Response } from 'supertest';

import app from '../app';
import app from '../../app';

interface ResponseBody {
message?: string;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import 'dotenv/config';
import request, { Response } from 'supertest';

import app from '../app';
import { stopDatabase } from '../database/mongo-common';
import app from '../../app';
import { stopDatabase } from '../../database/mongo-common';

// Define expected response shapes
interface AuthResponse {
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import 'dotenv/config';
import request, { Response } from 'supertest';

import app from '../app'; // Adjust the path as necessary
import { stopDatabase } from '../database/mongo-common';
import app from '../../app'; // Adjust the path as necessary
import { stopDatabase } from '../../database/mongo-common';

interface Store {
_id?: string; // Optionally include the ID in responses
Expand Down
50 changes: 50 additions & 0 deletions src/__tests__/unit/errorHandler.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { Request, Response } from 'express';

import errorHandler from '../../midleware/errorHandler';

describe('errorHandler middleware', () => {
const mockReq = {} as Request;

let mockStatus: jest.Mock;
let mockJson: jest.Mock;
let mockRes: Response;

beforeEach(() => {
mockStatus = jest.fn().mockReturnThis();
mockJson = jest.fn();

mockRes = {
json: mockJson,
status: mockStatus,
} as unknown as Response;
});

const mockNext = jest.fn();

it('should respond with 500 and error message in non-production', () => {
process.env.NODE_ENV = 'development'; // or 'test'
const err = new Error('Something went wrong');

errorHandler(err, mockReq, mockRes, mockNext);

expect(mockStatus).toHaveBeenCalledWith(500);
expect(mockJson).toHaveBeenCalledWith(
expect.objectContaining({
error: 'Something went wrong',
message: 'Internal Server Error',
})
);
});

it('should not include error details in production', () => {
process.env.NODE_ENV = 'production';
const err = new Error('Production error');

errorHandler(err, mockReq, mockRes, mockNext);

expect(mockStatus).toHaveBeenCalledWith(500);
expect(mockJson).toHaveBeenCalledWith({
message: 'Internal Server Error',
});
});
});
38 changes: 38 additions & 0 deletions src/__tests__/unit/git-user-name.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { execSync } from 'child_process';

import getGitUserName from '../../utils/git-user-name';

jest.mock('child_process');

describe('getGitUserName', () => {
afterEach(() => {
jest.resetAllMocks();
delete process.env.GITHUB_ACTIONS;
delete process.env.GITHUB_ACTOR;
});

it('returns GITHUB_ACTOR when running in GitHub Actions', () => {
process.env.GITHUB_ACTIONS = 'true';
process.env.GITHUB_ACTOR = 'github-test-user';
expect(getGitUserName()).toBe('github-test-user');
});

it('returns "github-actions" if GITHUB_ACTOR is missing in GitHub Actions', () => {
process.env.GITHUB_ACTIONS = 'true';
delete process.env.GITHUB_ACTOR;
expect(getGitUserName()).toBe('github-actions');
});

it('returns git config user.name when not in GitHub Actions', () => {
(execSync as jest.Mock).mockReturnValue('Test User\n');
expect(getGitUserName()).toBe('Test User');
expect(execSync).toHaveBeenCalledWith('git config --get user.name', { encoding: 'utf8' });
});

it('returns "unknown" if execSync throws', () => {
(execSync as jest.Mock).mockImplementation(() => {
throw new Error('fail');
});
expect(getGitUserName()).toBe('unknown');
});
});
37 changes: 37 additions & 0 deletions src/__tests__/unit/stores.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// tests/database/stores.test.ts
import { ObjectId } from 'mongodb';

import { getDatabase } from '../../database/mongo-common';
import { deleteStore, updateStore } from '../../database/stores';

jest.mock('../../database/mongo-common');

const mockCollection = {
deleteOne: jest.fn(),
findOne: jest.fn(),
updateOne: jest.fn(),
};

(getDatabase as jest.Mock).mockResolvedValue({
collection: () => mockCollection,
});

describe('stores.ts unit tests', () => {
beforeEach(() => {
jest.clearAllMocks();
});

it('should return "No store found with that id" if delete count is 0', async () => {
mockCollection.deleteOne.mockResolvedValueOnce({ deletedCount: 0 });
const response = await deleteStore(new ObjectId().toHexString());
expect(response).toEqual({ message: 'No store found with that id' });
});

it('should return null if store not found after update', async () => {
mockCollection.updateOne.mockResolvedValueOnce({});
mockCollection.findOne.mockResolvedValueOnce(null);

const result = await updateStore(new ObjectId().toHexString(), { name: 'Updated' });
expect(result).toBeNull();
});
});
2 changes: 0 additions & 2 deletions src/midleware/errorHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ import { NextFunction, Request, Response } from 'express';
// using _ to indicate that the parameter is not used
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const errorHandler = (err: Error, _req: Request, res: Response, _next: NextFunction): void => {
console.error(`[ERROR] ${err.stack ?? 'No stack trace available'}`);

const response = {
message: 'Internal Server Error',
...(process.env.NODE_ENV !== 'production' && { error: err.message }),
Expand Down
2 changes: 1 addition & 1 deletion src/utils/git-user-name.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ function getGitUserName(): string {
const name = execSync('git config --get user.name', { encoding: 'utf8' }).trim();
return name || 'unknown';
} catch (err) {
console.info('Git user name not found, returning "unknown"', err);
console.error('Error getting git user name:', err);
return 'unknown';
}
}
Expand Down