test: adding supertest (jest) to test API

This commit is contained in:
Ravinou 2025-02-23 16:07:01 +01:00
commit 5ce6e2c19c
No known key found for this signature in database
GPG key ID: EEEE670C40F6A4D7
7 changed files with 6618 additions and 2244 deletions

8
jest.config.js Normal file
View file

@ -0,0 +1,8 @@
/** @type {import('ts-jest').JestConfigWithTsJest} **/
export const testEnvironment = 'node';
export const transform = {
'^.+\\.tsx?$': ['ts-jest', {}],
};
export const moduleNameMapper = {
'^~/(.*)$': '<rootDir>/$1',
};

4460
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -6,6 +6,8 @@
"dev": "next dev",
"build": "next build",
"start": "next start",
"test": "jest",
"test:watch": "jest --watch",
"lint": "next lint",
"setup": "npm install && npm run setup:hooks",
"setup:hooks": "npx husky install",
@ -32,11 +34,19 @@
"devDependencies": {
"@commitlint/cli": "^19.7.1",
"@commitlint/config-conventional": "^19.7.1",
"@types/bcryptjs": "^2.4.6",
"@types/jest": "^29.5.14",
"@types/node": "^22.10.2",
"@types/nodemailer": "^6.4.17",
"@types/react": "^18.3.18",
"@types/supertest": "^6.0.2",
"eslint-config-next": "^15.1.6",
"husky": "^9.1.7",
"jest": "^29.7.0",
"node-mocks-http": "^1.16.2",
"prettier": "^3.5.1",
"supertest": "^7.0.0",
"ts-jest": "^29.2.6",
"typescript": "^5.7.2"
}
}

View file

@ -16,7 +16,10 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
try {
const transporter = nodemailerSMTP();
const mailData = emailTest(session.user?.email, session.user?.name);
if (!session.user?.email || !session.user?.name) {
return res.status(400).json({ message: 'User email or name is missing' });
}
const mailData = emailTest(session.user.email, session.user.name);
const info = await transporter.sendMail(mailData);
console.log(info);

View file

@ -1,3 +1,7 @@
## BATS tests against bash scripts
From `tests/bats`, launch `docker compose up --build`
## supertest (Jest) is used to test API endpoints
Launch `npm test`

View file

@ -0,0 +1,40 @@
import { createMocks } from 'node-mocks-http';
import handler from '~/pages/api/account/sendTestEmail';
import { getServerSession } from 'next-auth/next';
jest.mock('next-auth/next');
jest.mock('~/helpers/functions/nodemailerSMTP', () => ({
__esModule: true,
default: jest.fn(() => ({
sendMail: jest.fn().mockResolvedValue({ messageId: 'fake-message-id' }),
})),
}));
describe('Email API', () => {
it('should return 401 if not authenticated', async () => {
// Mock unauthenticated session
(getServerSession as jest.Mock).mockResolvedValue(null);
// Simulate a POST request
const { req, res } = createMocks({ method: 'POST' });
await handler(req, res);
// Expect 401 unauthorized
expect(res._getStatusCode()).toBe(401);
});
it('should send an email if authenticated', async () => {
// Mock unauthenticated session
(getServerSession as jest.Mock).mockResolvedValue({
user: { email: 'ada-lovelace@example.com', name: 'Lovelace' },
});
// Simulate a POST request
const { req, res } = createMocks({ method: 'POST' });
await handler(req, res);
// Expect 200 and a success message
expect(res._getStatusCode()).toBe(200);
expect(res._getJSONData()).toEqual({ message: 'Mail successfully sent' });
});
});

View file

@ -13,11 +13,6 @@ declare module 'next-auth' {
id?: string;
} & DefaultSession['user'];
}
interface JWT {
roles?: string[];
id?: string;
}
}
export enum SessionStatus {