我是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"
}
}
]
createConnection.ts
import {createConnection, getConnectionOptions} from "typeorm";
export const createConnection = async () => {
const createConnectionOptions = await getConnectionOptions(process.env.NODE_ENV);
return createConnection({...createConnectionOptions,name:"default"});
}
testClass.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();
}
关于jestjs - 如何在beforeAll()中调用数据库连接,并在afterAll()中关闭数据库连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55651260/