@nestjs/testing 访问真实数据库postgres

问题描述

我正在尝试对我的 nestjs(打字稿)项目中的控制器进行 e2e 测试,我正在使用 knex,并且 postgres。 所以我为控制器制作了一个 .spec 文件(比如:ProductsController)和一个 dbConfig.ts 文件

import re
a = ['abc1','2def','g3h']
[re.sub("\d+","",x) for x in a]

然后我使用这个 db 对象在 beforeEach 中运行 migrationsseeds删除了表在 afterEach 中,然后在其中一项测试中,我使用此对象从表产品中进行选择,并且 有效

bcz 我正在做 e2e 测试 现在我想测试路径 "/products" 调用 productService 中的一个方法,该方法调用 productClient 中的另一个方法(我实现了这样就可以了)。

但是 ProductClient 有一个构造函数,它注入我们在我们的应用程序中使用的 knex 对象来访问 postgres 数据库(不同于 db 对象),如下所示:

import * as Knex from 'knex';
export const config = {
  client: 'sqlite3',connection: ':memory:',useNullAsDefault: true,migrations: {
    directory: 'src/db/test-migrations',tableName: 'knex_migrations',extension: 'ts',},seeds: {
    directory: 'src/db/test-seeds',};

let db = null;
console.log('config',config)
if (process.env.NODE_ENV === 'test') {
  console.log('process.env.NODE_ENV',process.env.NODE_ENV)
  db = new (Knex as any)(config);
}

module.exports = db;

其他客户端类可能会像这样注入: constructor(private readonly knexService: KnexService) { this.knex = knexService.getKnexConnection(); }

无论如何,在 knex 的配置中,我用 db 的相同配置替换了 knex/postgres 配置(见上文), 通过这种方式,我让 ProductClient 访问我在运行测试时创建的内存数据库

结果我得到了这个 constructor(@Inject(KNEX_CONNECTION) private readonly knex: Knex) {}

解决方法

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

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

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