jestjs - 如何在beforeAll()中调用数据库连接,并在afterAll()中关闭数据库连接

标签 jestjs typeorm

我是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/

相关文章:

testing - 开 Jest 忽略除 1 个包之外的所有 node_modules

postgresql - 查询失败错误 : insert or update on table "graph" violates foreign key constraint "FK_0e40......"

typescript - 我可以使用部分实体通过 typeorm 进行保存吗?

javascript - 如何测试调用外部 api 的 redux-saga 生成器?

javascript - 用 Jest 模拟 require 语句

jestjs - Jest 全局变量示例

javascript - 嵌套 : Cannot create a new connection named "default",,因为使用该名称的连接已经存在,并且它现在有一个事件的连接 session

reactjs - Jest 设置 "SyntaxError: Unexpected token export"

javascript - 如何异步查询多条SQL?

nestjs - Nest 无法解析 JwtStrategy 的依赖关系