Mik*_*maa 2 jestjs typeorm nestjs
我希望在每次测试或测试运行开始时创建数据库表,以便 1) 所有迁移都针对测试数据库运行,或者 2) 单个迁移设置所有表(更快)。这与 Django 的做法类似。
\n\n有没有一种方法可以使用 TypeORM 轻松实现自动化,这样我就不需要手动维护测试数据库的副本?当然,在测试结束时,需要进行相反的拆卸和表清理。
\n\n目前,我的测试失败:
\n\n\xe2\x97\x8f User \xe2\x80\xba GET /users \xe2\x80\xba should return an array of users\n\n QueryFailedError: relation "user" does not exist\n\n at new QueryFailedError (../src/error/QueryFailedError.ts:9:9)\n at Query.callback (../src/driver/postgres/PostgresQueryRunner.ts:178:30)\n at Query.Object.<anonymous>.Query.handleError (../node_modules/pg/lib/query.js:145:17)\n at Connection.connectedErrorMessageHandler (../node_modules/pg/lib/client.js:214:17)\n at Socket.<anonymous> (../node_modules/pg/lib/connection.js:134:12)\n
Run Code Online (Sandbox Code Playgroud)\n\n显然...如果我手动对数据库运行迁移,则不会失败e2e_test
。
我的测试代码:
\n\n\xe2\x97\x8f User \xe2\x80\xba GET /users \xe2\x80\xba should return an array of users\n\n QueryFailedError: relation "user" does not exist\n\n at new QueryFailedError (../src/error/QueryFailedError.ts:9:9)\n at Query.callback (../src/driver/postgres/PostgresQueryRunner.ts:178:30)\n at Query.Object.<anonymous>.Query.handleError (../node_modules/pg/lib/query.js:145:17)\n at Connection.connectedErrorMessageHandler (../node_modules/pg/lib/client.js:214:17)\n at Socket.<anonymous> (../node_modules/pg/lib/connection.js:134:12)\n
Run Code Online (Sandbox Code Playgroud)\n\n\n
看起来可以connection
从 TypeORM 中捞出然后调用它的synchronise
方法。
如果有人 1) 知道获得连接的更好方法 2) 知道现在是否是打电话的合适时间,synchronise
请发表评论。
describe('User', () => {
let app: INestApplication;
let repository: Repository<User>;
beforeAll(async () => {
const module = await Test.createTestingModule({
imports: [
UserModule,
TypeOrmModule.forRoot({
type: 'postgres',
host: 'localhost',
port: 54320,
username: 'local_dev',
password: 'local_dev',
database: 'e2e_test',
entities: ['./**/*.entity.ts'],
synchronize: false,
}),
],
}).compile();
app = module.createNestApplication();
repository = module.get('UserRepository');
const connection = repository.manager.connection;
// dropBeforeSync: If set to true then it drops the database with all its tables and data
await connection.synchronize(true);
await app.init();
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6407 次 |
最近记录: |