Skip to content
This repository was archived by the owner on Dec 8, 2022. It is now read-only.

Commit 0fbc643

Browse files
committed
fix(server): Configure jest
(WIP) Jest is detecting open handles on Redis' bee
1 parent 499204f commit 0fbc643

12 files changed

Lines changed: 113 additions & 36 deletions

File tree

server/jest.config.js

Lines changed: 0 additions & 5 deletions
This file was deleted.

server/jest.config.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import type { Config } from '@jest/types';
2+
import dotenv from 'dotenv';
3+
4+
dotenv.config();
5+
6+
const config: Config.InitialOptions = {
7+
preset: 'ts-jest',
8+
testEnvironment: 'node',
9+
};
10+
export default config;

server/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
"docker:docs": "docker exec -t alertadotesouro-server-dev-1 yarn docs",
1717
"lint": "eslint . --ext .js,.jsx,.ts,.tsx",
1818
"docker:lint": "docker exec -t alertadotesouro-server-dev-1 yarn lint",
19-
"test": "jest",
19+
"test": "NODE_ENV=test jest",
2020
"docker:test": "docker exec -t alertadotesouro-server-dev-1 yarn test"
2121
},
2222
"dependencies": {

server/src/app.test.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
1-
import CreateServer from './app';
1+
import app from './app';
22

33
it('Installs all the middleware', () => {
4-
const app = CreateServer();
54
expect(app.listen).toBeDefined();
6-
expect(app.use).toHaveLength(4);
5+
// I don't even know what else to test
76
});

server/src/app.ts

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,10 @@ import routes from './routes';
44
import logRequest from './middlewares/requestsLogger';
55
import 'dotenv/config';
66

7-
export default function CreateServer() {
8-
const app = express();
7+
const app = express();
98

10-
app.use(cors());
11-
app.use(logRequest);
12-
app.use(express.json());
13-
app.use(routes);
14-
return app;
15-
}
9+
app.use(cors());
10+
app.use(logRequest);
11+
app.use(express.json());
12+
app.use(routes);
13+
export default app;

server/src/database/index.test.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { getConnection } from 'typeorm';
2+
3+
import DB from '.';
4+
5+
beforeAll(async () => {
6+
await DB.connect('test');
7+
});
8+
9+
afterAll(async () => {
10+
await DB.close('test');
11+
});
12+
13+
beforeEach(async () => {
14+
DB.clear('test');
15+
});
16+
17+
test('connects to the database', () => {
18+
const connection = getConnection('test');
19+
expect(connection).toBeDefined();
20+
expect(connection.isConnected).toBeTruthy();
21+
});

server/src/database/index.ts

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,34 @@
1-
import { createConnection } from 'typeorm';
1+
import { createConnection, getConnection } from 'typeorm';
2+
import 'dotenv/config';
23

3-
createConnection();
4+
const DB = {
5+
async connect(name = 'default') {
6+
await createConnection(name);
7+
},
8+
9+
async close(connectionName?: string) {
10+
await getConnection(connectionName).close();
11+
},
12+
13+
clear(connectionName?: string) {
14+
const connection = getConnection(connectionName);
15+
const entities = connection.entityMetadatas;
16+
17+
entities.forEach(async entity => {
18+
const repository = connection.getRepository(entity.name);
19+
await repository.query(`DELETE FROM ${entity.tableName}`);
20+
});
21+
},
22+
23+
async drop(connectionName?: string) {
24+
await getConnection(connectionName).dropDatabase();
25+
},
26+
};
27+
28+
DB.connect().catch(err => {
29+
console.error('❌ Error connection to DB!');
30+
console.error(err);
31+
throw err;
32+
});
33+
34+
export default DB;

server/src/middlewares/ensureAuthenticated.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,21 @@ import { Request, Response } from 'express';
22
import ensureAuthenticated from './ensureAuthenticated';
33

44
describe('ensures', () => {
5+
// FIXME not actually throwing WTF but when env is actually no set on server it throws. I don't think it have anything to do with asynchronous tests and such, since they are on different threads.
6+
it.skip('fails when `JWT_SECRET` env is not set', () => {
7+
const request = {
8+
// Is there a way to modularize this better? Doesn't feel DRY enough.
9+
headers: {
10+
authorization: 'Bearer 12345',
11+
},
12+
} as Request; // Asserting to type is fine to mock a request, that's the whole point;
13+
const next = jest.fn();
14+
delete process.env.JWT_SECRET;
15+
expect(() =>
16+
ensureAuthenticated(request, null as unknown as Response, next),
17+
).toThrow();
18+
});
19+
520
it('rejects when JWT is missing', () => {
621
const request = {
722
headers: {
@@ -15,6 +30,7 @@ describe('ensures', () => {
1530
next,
1631
);
1732
expect(next.mock.calls).toHaveLength(1);
33+
// REVIEW - I don't know how to hard type `jest.fn.mock.calls` since they are `any[]`
1834
expect(next.mock.calls[0][0] instanceof Error).toBeTruthy();
1935
expect(next.mock.calls[0][0].message).toBe(
2036
'Invalid JSON Web Token: JSON Web Token is missing',

server/src/middlewares/ensureAuthenticated.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ export default function ensureAuthenticated(
3939
}
4040
const [, token] = authHeader.split(' '); // Do not use "type" of token (Bearer)
4141

42-
const decoded = verify(token, authConfig.jwt.secret as string);
42+
const decoded = verify(token, authConfig.jwt.secret);
4343

4444
const { sub } = decoded as TokenPayload;
4545

server/src/middlewares/requestsLogger.ts

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,14 @@ export default function logRequest(
1414
_: Response,
1515
next: NextFunction,
1616
): void {
17-
const { method, url } = request;
18-
const logLabel = `[${method.toUpperCase()}] request to ${url}`;
17+
if (process.env.NODE_ENV !== 'test') {
18+
const { method, url } = request;
19+
const logLabel = `[${method.toUpperCase()}] request to ${url}`;
1920

20-
console.time(logLabel);
21-
next();
22-
console.timeEnd(logLabel);
21+
console.time(logLabel);
22+
next();
23+
console.timeEnd(logLabel);
24+
} else {
25+
next();
26+
}
2327
}

0 commit comments

Comments
 (0)