I’m using TypeORM and ExpressJS. I’m encountering an issue while attempting to access the database in a test file. Whenever I encounter an error, it says that the entities is not found.
Here’s my index.ts file:
import './config';
import express from 'express';
import morgan from 'morgan';
import cors from 'cors';
import initRoutes from './routes';
import { AppDataSource } from './utils/data-source';
import CreateUser from './seeder/createUser';
const app = express();
const PORT = process.env.APP_PORT;
let server: any;
const startServer = () => {
server = app.listen(PORT, () => {
console.log(`App starting at PORT ${PORT}`);
});
};
const setupMiddlewares = () => {
// CORS middleware
app.use(cors());
// Enable logger (morgan)
app.use(morgan('[:date[clf]] :method :url :status :res[content-length] - :response-time ms'));
// Request body parsing middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
};
const startDatabase = async () => {
try {
await AppDataSource.initialize();
} catch (error) {
console.log('Error while connecting the database', error);
process.exit(0);
}
};
const startApp = async () => {
// Start Database
await startDatabase();
// Add Default user in database
await CreateUser();
// Start Server
startServer();
// Setup Global middleware
setupMiddlewares();
// Initialize routes
initRoutes(app);
// Export the app instance after everything is set up
return app;
};
const closeApp = async () => {
try {
// Close the server
await server.close();
// Destroy the AppDataSource
await AppDataSource.destroy();
} catch (error) {
console.error('Error closing app:', error);
}
};
startApp();
export { startApp, closeApp };
And here’s my test file:
import request from "supertest";
import { startApp, closeApp } from "../src/index";
describe('Todo API', () => {
let app;
beforeAll(async () => {
app = await startApp();
});
afterAll(async () => {
await closeApp();
});
it('healthcheck', async () => {
const res = await request(app)
.get('/healthcheck')
expect(res.statusCode).toEqual(200);
});
});
And here’s the error I’m receiving:
Error Image
You can see in this error EntityMetadataNotFoundError: No metadata for "User" was found.
since we are creating a default user inside the startApp function.
Note: My app is working fine, but I only encounter issues when I run my test cases. I don’t know why, but somehow my TypeORM is not properly making a connection with my database.
I expect to run test cases for my API.
Bhavesh Sharma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.