This is my index.ts
import "reflect-metadata";
import {createConnection, Server} from "typeorm";
import express from "express";
import * as bodyParser from "body-parser";
import routes from "./routes/routes";
import cors from 'cors';
const init = () => createConnection().then( async () => {
const app = express();
// create express app
app.use(bodyParser.json());
app.use(cors());
// register express routes from defined application routes
app.use("/", routes);
app.listen(3000);
console.log("Express server has started on port 3000.");
return app;
}).catch(error => console.log(error));
export default init;
And I want to import init inside my tests,
import chai from 'chai';
import chaiHttp from 'chai-http';
import init from '..';
chai.use(chaiHttp);
chai.should();
let app;
describe("TESTS", () => {
before(async () => {
app = await init();
});
describe("GET /posts", () => {
//Test to get all posts
it("Should get all posts", (done) => {
chai.request(app)
.get('/posts')
.end((err, response) => {
response.should.have.status(200);
response.body.should.be.a('object');
done();
});
});
});
});
This code is working, but I want to clese the connection at the end of the test whit server.close
(server is the returned object of app.listen()) But I don know how to export that object, when I try something like
return {app: app, server: server}
I get an error when I try to use it inside my tests.
Property 'app' does not exist on type 'void | { app: Express; server: Server; }'.
I try to specify the return type of init() but I get errors... I think I don't know how to do it.
I solved it. Thank you @Aluan Haddad you guide my to the right path.
I use try catch inside the function and change some small things.
const init = createConnection().then( async () => {
try {
const app = express();
// create express app
app.use(bodyParser.json());
app.use(cors());
// register express routes from defined application routes
app.use("/", routes);
const server = app.listen(3000);
console.log("Express server has started on port 3000.");
return {app, server};
} catch (e) {
console.log(e);
}
});
describe("TESTS", () => {
before(async function() {
console.log("Before executed")
const appData = await init;
app = appData.app;
server = appData.server;
});
after(() => {
server.close();
console.log("After executed")
});
}
If I'm making something wrong plis tell me