使用TypeORM和ormconfig.js + syncronize在NestJS中设置e2e测试

问题描述

我正在寻找在基本的hello-world NestJS项目中设置e2e测试的帮助。我将应用程序的根文件夹中的ormconfig.js文件用于数据库配置,因为我使用事务,并且必须能够从命令行运行typeorm cli。那是ormconfig.js

/* eslint-disable @typescript-eslint/no-var-requires */
const config = require('config')
const path = require('path')
/* eslint-enable */

const dbConfig = config.get('db')

module.exports = {
  type: dbConfig.type,host: dbConfig.host,port: dbConfig.port,username: dbConfig.username,password: dbConfig.password,database: dbConfig.database,syncronize: dbConfig.syncronize,dropSchema: dbConfig.dropSchema,entities: [path.join(__dirname,'dist','entities','*.{ts,js}')],migrations: [path.join(__dirname,'migrations',js}')]
}

然后,我有一个非常基本的app.module.ts

import { Module } from '@nestjs/common'
import { TypeOrmModule } from '@nestjs/typeorm'
import { AuthModule } from '../auth/auth.module'

@Module({
  imports: [TypeOrmModule.forRoot(),AuthModule]
})
export class AppModule {}

最后,这是e2e测试文件:

import { INestApplication } from '@nestjs/common'
import { Test,TestingModule } from '@nestjs/testing'
import * as request from 'supertest'
import { AppModule } from '../src/app/app.module'

describe('AppController (e2e)',() => {
  let app: INestApplication

  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule]
    }).compile()
    app = moduleFixture.createNestApplication()
    await app.init()
  })

  it('/auth/signup (POST) should sign up the user',() => {
    return request(app.getHttpServer())
      .post('/auth/signup')
      .send({
        email: '[email protected]',password: '123123qQ'
      })
      .expect(201)
  })

  afterAll(async () => {
    await app.close()
  })
})

我可以运行迁移和应用程序本身,但是当尝试运行e2e测试时,我得到了 EntityMetadataNotFound: No metadata for "User" was found.

我猜想,TypeORM在测试期间会以不同的方式处理配置。我尝试了不同的方式来建立连接,而最有效的方法似乎是手动设置实体:

app.module.ts:
...
import * as typeOrmConfig from '../../ormconfig'
import { User } from '../entities/user'

@Module({
  imports: [
    TypeOrmModule.forRoot({
      ...typeOrmConfig,entities: [User]
    }),AuthModule
  ]
})
export class AppModule {}

指定所有实体并不方便(我正在寻找避免这种情况的方法),但是至少我要进行下一步,现在的错误是ER_NO_SUCH_TABLE。我有用于测试的单独数据库,它是空的。但是TypeORM中有syncronize: true用于测试。 syncronize是否存在一些异步问题?是否有可能以某种方式获得对连接对象的访问并在beforeAll中等待connection.syncronize(true)?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)