GAミント至上主義

Web Monomaniacal Developer.

NestJSでテスト用DB接続を使ったテスト実行時のNest could not find testConnection element エラーの対処

NestJS + TypeORMの環境で、e2eテスト実行時に、テスト用接続情報を下記のように使用したところエラーが出た。
ググっても記事出てこないのでメモ。

app.e2e-spec.ts
```
import { getConnectionOptions } from 'typeorm'

//省略
describe('UsersController (e2e)', () => {
let app: INestApplication

beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [
UsersModule,
TypeOrmModule.forRootAsync({
useFactory: async () => {
return await getConnectionOptions('test')
},
}),
],
exports: [TypeOrmModule],
providers: [],
}).compile()
app = module.createNestApplication()
await app.init()
})
//省略
```

実行時のエラー
```
$ yarn test:e2e
yarn run v1.22.10
$ jest --config ./test/jest-e2e.json
FAIL test/app.e2e-spec.ts (8.139 s)


● Test suite failed to run

Nest could not find testConnection element (this provider does not exist in the current context)

at InstanceLinksHost.get (../node_modules/@nestjs/core/injector/instance-links-host.js:15:19)
at Object.find (../node_modules/@nestjs/core/injector/module-ref.js:38:55)
at Object.get (../node_modules/@nestjs/core/injector/module.js:345:28)
at TypeOrmCoreModule. (../node_modules/@nestjs/typeorm/dist/typeorm-core.module.js:96:47)
at ../node_modules/@nestjs/typeorm/dist/typeorm-core.module.js:20:71
at Object..__awaiter (../node_modules/@nestjs/typeorm/dist/typeorm-core.module.js:16:12)
at TypeOrmCoreModule.onApplicationShutdown (../node_modules/@nestjs/typeorm/dist/typeorm-core.module.js:92:16)
at Object.callAppShutdownHook (../node_modules/@nestjs/core/hooks/on-app-shutdown.hook.js:51:35)
```


下記のようなormconfig.tsを使用してdefaultとtestを書いており、getConnectionOptionsでtestの方を使用していた。
```
// https://github.com/typeorm/typeorm/blob/master/docs/connection-options.md
module.exports = [
{
name: 'default',
type: 'mysql',
host: process.env.DB_HOST,
port: process.env.DB_PORT,
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
logging: process.env.DB_LOGGING,
synchronize: process.env.DB_SYNCHRONIZE,
migrationsRun: process.env.DB_MIGRATIONS_RUN,
entities: ['src/**/*.entity.ts'],
migrations: ['src/migration/*.ts'],
migrationsTableName: 'migrations',
cli: {
migrationsDir: 'src/migration',
},
},
{
name: 'test',
type: 'mysql',
host: process.env.TEST_DB_HOST,
port: process.env.TEST_DB_PORT,
username: process.env.TEST_DB_USERNAME,
password: process.env.TEST_DB_PASSWORD,
database: process.env.TEST_DB_DATABASE,
synchronize: false,
dropSchema: true,
entities: ['src/**/*.entity.ts'],
migrationsRun: true,
migrations: ['src/migration_test/*.ts'],
logging: false,
},
]
```

エラーのtestConnection からわかるように自動的に生成されるはずのものっぽいのが見つからないということで、nameを消してみたところ解決できた。
nameは必要だけどいろいろ邪魔になるっぽい。
getConnectionOptionsの返り値は全部realonlyなので新しいオブジェクトでnameをnullにして返した。

```
useFactory: async () => {
const options = await getConnectionOptions('test')
return {
...options,
// いろいろエラーの原因になるっぽいので消す
name: null,
}
},
```