如何在 beforeAll() 中调用 DB 连接,并在 After All() 中调用 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"
    }
  }
]

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();
}

你正在混合模式。 如果您使用的是 N 个连接。 不要创建"默认"连接,而是在 ormconfig.json 中创建三个命名连接。

完成此操作后 - 在配置中,您可以使用name(在您的示例中为 hello(来查找和加载配置。


beforeEach(async () => {
  await TypeORM.createConnection('connection1Name')
  await TypeORM.createConnection('connection2Name')
  await TypeORM.createConnection('connection3Name')
})
afterEach(async () => {
  await getConnection('connection1Name').close()
  await getConnection('connection2Name').close()
  await getConnection('connection3Name').close()
})
// in your tests you can find use getConnection('name') to use the specific connection

如果要在每次测试之前移动连接代码,可以使用beforeEachafterEach。您还可以构建测试,以便在将每个测试应用于describe范围内的测试之前。

// Applies to all tests in this file
beforeEach(() => {
  return initializeCityDatabase();
});
test('city database has Vienna', () => {
  expect(isCity('Vienna')).toBeTruthy();
});
describe('matching cities to foods', () => {
  // Applies only to tests in this describe block
  beforeEach(() => {
    return initializeFoodDatabase();
  });
  test('Vienna <3 sausage', () => {
    expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true);
  });
});

来源: https://jestjs.io/docs/en/setup-teardown.html

  • 我们将测试设置移动到另一个文件,并在其中初始化并导出 Apollo 服务器和数据库连接(作为异步立即调用的函数(。

  • 在我们的测试中beforeEach/afterEach中,我们等待连接并在完成后关闭它。

你觉得怎么样?

resolvers.test.ts

process.env.NODE_ENV = 'test';
import { gql } from 'apollo-server-express';
import { connection } from '../../utils/testEnv';
import { server } from '../../utils/testEnv';
import mongoose from 'mongoose';
let db: typeof mongoose;
beforeAll(async () => {
   db = await connection;
})
   
afterAll(async () => {
   await db.connection.close();
})
   
describe("Resolvers tests", () => {
   it("Throw user with no context",  async () => {
      
      const expectedErrorMessage = 'Not logged in';
      const query = gql`{ 
                           user {
                              firstName
                           } 
                        }
                     `;
      const result = await server.executeOperation({
         query: query,
      })
  expect(result.errors[0].message).toEqual(expectedErrorMessage);
})

testEnv.ts

import  mongoose from "mongoose";
import typeDefs from '../schemas/typeDefs';
import resolvers from '../schemas/resolvers';
const { ApolloServer } = require('apollo-server-express');
const {authMiddleware} = require('../utils/auth');
export const server: typeof ApolloServer = new ApolloServer(
   {
      resolvers, 
      typeDefs, 
      context: authMiddleware}, 
   {  
      stopGracePeriodMillis: Infinity
   }
);
export const connection = (async function connect() {
   return await mongoose.connect(process.env.MONGO_TEST_CONNECTION, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useCreateIndex: true,
      useFindAndModify: false,
    })})();

最新更新