vendredi 10 juillet 2020

How can I test my express/typeorm app whit mocha?

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.

Aucun commentaire:

Enregistrer un commentaire