test(core): add tests for nested transient structures

This commit is contained in:
Kamil Myśliwiec
2025-07-30 17:07:00 +02:00
parent f14a976051
commit a9d5716dad

View File

@@ -1,4 +1,4 @@
import { INestApplication, Scope } from '@nestjs/common';
import { INestApplication, Injectable, Scope } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { expect } from 'chai';
import * as request from 'supertest';
@@ -17,7 +17,8 @@ class Meta {
}
describe('Transient scope', () => {
let server;
describe('when transient scope is used', () => {
let server: any;
let app: INestApplication;
before(async () => {
@@ -36,7 +37,7 @@ describe('Transient scope', () => {
await app.init();
});
describe('when one service is request scoped', () => {
describe('and when one service is request scoped', () => {
before(async () => {
const performHttpCall = end =>
request(server)
@@ -78,4 +79,64 @@ describe('Transient scope', () => {
after(async () => {
await app.close();
});
});
describe('when there is a nested structure of transient providers', () => {
let app: INestApplication;
@Injectable({ scope: Scope.TRANSIENT })
class DeepTransient {
public initialized = false;
constructor() {
this.initialized = true;
}
}
@Injectable({ scope: Scope.TRANSIENT })
class LoggerService {
public context?: string;
}
@Injectable({ scope: Scope.TRANSIENT })
class SecondService {
constructor(public readonly loggerService: LoggerService) {
this.loggerService.context = 'SecondService';
}
}
@Injectable()
class FirstService {
constructor(
public readonly secondService: SecondService,
public readonly loggerService: LoggerService,
public readonly deepTransient: DeepTransient,
) {
this.loggerService.context = 'FirstService';
}
}
before(async () => {
const module = await Test.createTestingModule({
providers: [FirstService, SecondService, LoggerService, DeepTransient],
}).compile();
app = module.createNestApplication();
await app.init();
});
it('should create a new instance of the transient provider for each provider', async () => {
const firstService1 = app.get(FirstService);
expect(firstService1.secondService.loggerService.context).to.equal(
'SecondService',
);
expect(firstService1.loggerService.context).to.equal('FirstService');
expect(firstService1.deepTransient.initialized).to.be.true;
});
after(async () => {
await app.close();
});
});
});