jestjs - 如何在 beforeAll() 中调用 DB 连接并在 afterAll() 中关闭 DB 连接
问题描述
我是 Jest 和 TypeORM 的新手,想使用 typeorm 和 Jest 开发数据库验证框架。如何在 beforeAll() 中调用三个数据库连接实例。
这是一个关于使用 TypeORM 和 Jest 进行数据库验证的新框架 Ormconfig.json 具有三个数据库的详细信息,并有一个用于数据库连接的 .ts 类和一个测试类。
ormconfig.json
[{
"name": "default",
"type": "mysql",
"host": "127.0.01",
"port": 3306,
"username": "sdf",
"password": "uuehfldjskh",
"database": "ifsdjh",
"synchronize": true,
"logging": false,
"entities": [
"src/entity/**/*.ts"
],
"migrations": [
"src/migration/**/*.ts"
],
"subscribers": [
"src/subscriber/**/*.ts"
],
"cli": {
"entitiesDir": "src/entity",
"migrationsDir": "src/migration",
"subscribersDir": "src/subscriber"
}
},
{
"name": "hello",
"type": "mysql",
"host": "127.0.01",
"port": 3306,
"username": "weqwe",
"password": "das",
"database": "dsfds",
"synchronize": true,
"logging": false,
"entities": [
"src/entity/**/*.ts"
],
"migrations": [
"src/migration/**/*.ts"
],
"subscribers": [
"src/subscriber/**/*.ts"
],
"cli": {
"entitiesDir": "src/entity",
"migrationsDir": "src/migration",
"subscribersDir": "src/subscriber"
}
}
]
创建连接.ts
import {createConnection, getConnectionOptions} from "typeorm";
export const createConnection = async () => {
const createConnectionOptions = await getConnectionOptions(process.env.NODE_ENV);
return createConnection({...createConnectionOptions,name:"default"});
}
测试类.ts
import {Patches} from "../entity/Patches";
import {createConnection} from "../utils/createConnection";
test('Query with getRepository()', async () => {
jest.setTimeout(100000);
const connection = await createConnection();
const Count = await connection.getRepository(User).count();
console.log(Count);
expect(Count).toEqual(32);
await connection.close();
})
如何在每次测试之前将连接移动到数据库 -
beforeAll(){
connectionDB();
}
test()
{
connection(db1) //connect to DB1
/** Do operation on DB1 **/
connection(db2) //connect to DB2
/** Do operation on DB2 **/
Compare both result of DB1 and DB2
}
afterAll()
{
connectionDB().close();
}
解决方案
伪代码:
let connection;
beforeAll(){
connection = connectionDB();
}
test() {
//...
}
afterAll() {
connection.close();
}
推荐阅读
- javascript - Syncfusion 无法从数据源呈现 Grid 行模板表达式值
- python - Wide_deep 分类器模型,需要预测概率值,而不只是“最佳猜测”
- angular - Navigation ID is not equal to the current router navigation id 错误
- python - 用python和pandas将CSV文件中的三列合二为一
- java - NFC 阅读器“SELECT(通过 AID)”APDU 未路由到 Android 设备
- ios - 如何在 Swift 3 中显示矩阵
- java - 在 JAVA watchservice api 中,我如何定位所有驱动器
- javascript - 对数组 vuejs 的每个值执行相同的操作
- c++ - macOS High Sierra 上的 libc++ 损坏
- associations - Sequelize ORM,Hooks 不与关联一起工作