Reputation: 143
I am building an API with nest. For E2E tests I am using Jest, in the beforeAll() I instantiate a complete NestJS application using createNestApplication from the AppModule:
const module = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = module.createNestApplication<NestFastifyApplication>(
new FastifyAdapter(),
);
await app.init();
Tests and validations are carried out with the app object. For some validations, and to delete records from the database after testing, I am looking for a way to get from the app object the repositories of my entities, or at least, the instance of TypeOrm that has the connection to the database.
Reviewing the object and its documentation I found that nestJS provides some methods to extract modules, or providers from this object, but I haven't seen anything to extract the DB connection instance. I tried to extract the TypeOrm module using the select method like this:
const typeOrmModule = app.select(TypeOrmModule);
But that causes the error: Nest could not select the given module (it does not exist in current context)
I don't want to have to generate a new connection to the DB knowing that the app object already has one. So I wonder if there is a way to extract that instance of the connection or the repositories that the object has inside. Thanks in advance
Upvotes: 3
Views: 3221
Reputation: 143
Jay McDoniel's comment guided me to find the solution. The method getRepositoryToken(Entity)
from @nestjs/typeorm
returns the token for the entitie's repo and with it I could get the repo I needed:
const repo = app.get<Repository<Entity>>(getRepositoryToken(Entity));
Upvotes: 7