FoalTS / foal

Full-featured Node.js framework, with no complexity. 🚀 Simple and easy to use, TypeScript-based and well-documented.
https://foalts.org/
MIT License
1.89k stars 139 forks source link

ConnectionManager does not work in unit testing #932

Closed vlourme closed 3 years ago

vlourme commented 3 years ago

Hello! I'm facing a problem with TypeORM ConnectionManager and FoalTS Unit Testing.

When running the project with npm run develop, everything works fine. But when trying unit testing, the connection to the DB is not made (using MongoDB).

Here are some files and logs from the project:

ormconfig.js

const { Config } = require('@foal/core');

module.exports = {
  type: 'mongodb',
  url: Config.get('database.url', 'string'),
  useNewUrlParser: true,
  useUnifiedTopology: true,
  logging: true,
  entities: ['./build/app/entities/*.entity.js'],
};

Logs after running npm run test:

[ ... ]
[1]   1) AuthController
[1]        has a "register" method that
[1]          should return an HttpResponseOK.:
[1]      ConnectionNotFoundError: Connection "default" was not found.
[1]       at new ConnectionNotFoundError (src/error/ConnectionNotFoundError.ts:8:9)
[1]       at ConnectionManager.get (src/connection/ConnectionManager.ts:40:19)
[1]       at Object.getMongoRepository (src/index.ts:308:35)
[1]       at Auth.findUser (src/app/services/auth.service.ts:9:24)
[1]       at Auth.userExists (src/app/services/auth.service.ts:20:26)
[1]       at Auth.addUser (src/app/services/auth.service.ts:24:20)
[1]       at AuthController.createUser (src/app/controllers/auth.controller.ts:20:55)
[1]       at Context.<anonymous> (src/app/controllers/auth.controller.spec.ts:36:44)
[1]       at processImmediate (node:internal/timers:464:21)

I'd be happy to create a pull request to fix the problem, I'm just lost actually to find where the issue comes from. Thank you!

LoicPoullain commented 3 years ago

Hi @vlourme

What is your test code? Do you call await createConnection() somewhere in your test ? For example with a before(async () => { await createConnection() });?

vlourme commented 3 years ago

Thank you for your fast answer! It effectively works.

I was able to make it common by adding this into the global test.ts file:

let connection: Connection;

before(async () => {
  console.log('Creating database connection');
  connection = await createConnection();
});

after(async () => {
  console.log('Closing database connection');
  await connection.close();
});