【发布时间】:2020-07-10 15:51:26
【问题描述】:
这是我的 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;
我想在我的测试中导入 init,
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();
});
});
});
});
此代码正在运行,但我想在测试结束时关闭连接server.close(服务器是 app.listen() 的返回对象)但我不知道如何导出该对象,当我尝试类似
return {app: app, server: server}
当我尝试在测试中使用它时出现错误。
Property 'app' does not exist on type 'void | { app: Express; server: Server; }'.
我尝试指定 init() 的返回类型,但出现错误...我想我不知道该怎么做。
【问题讨论】:
-
这是你使用的
catch。Promise.protoype.catch收到一个错误并通过返回一个回退值来处理它。console.log()返回void所以init的类型返回类型变为typeof app | void -
我可以将所有的内容放在一个 try/catch 块中吗?并解决问题@AluanHaddad(对不起,如果我的英语不是最好的)
标签: typescript testing mocha.js typeorm