nest
nest copied to clipboard
Overide providers from imported module (not in testing context)
Is there an existing issue for this?
- [X] I have searched the existing issues
Current behavior
I am trying to override a provider imported into module B from module A by provding an override of the said provider in the Module decorator of module B.
However when I am trying to get an instance of the provider by a token, I am always getting the provider definition as given in Module A, instead of the Module B.
I have created a sample repo with the failing test @ https://github.com/chandu/nest-override-modules Te be speicifc this file: https://github.com/chandu/nest-override-modules/blob/main/src/override.spec.ts#L7
Snippet of the code is below:
import { Module } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { describe, it, expect } from 'vitest';
const tokenSymbol = Symbol('Some-Token');
describe('NestJs Override Modules', () => {
describe('Can override a provider imported via a module', () => {
it('should work', async () => {
@Module({
providers: [{ provide: tokenSymbol, useValue: 'Batman' }],
})
class FirstModule {}
@Module({
imports: [FirstModule],
providers: [{ provide: tokenSymbol, useValue: 'Robin' }],
exports: [tokenSymbol],
})
class SecondModule {}
const moduleRef = await Test.createTestingModule({
imports: [SecondModule],
}).compile();
const value = moduleRef.get(tokenSymbol);
expect(value).toEqual('Robin');
});
});
});
Minimum reproduction code
https://github.com/chandu/nest-override-modules
Steps to reproduce
pnpm install
pnpm test
Expected behavior
I assumed that the provider definitions are resolved in a hierarchical way, i.e look for the provider in current module, if not found look into the providers that are expored from the imported modules etc.
I would have expected the value resolved from the container for the token to be 'Robin' instead of 'Batman' in the code snippet above. But it's always resolving the value 'Batman' though this provider is not exported at all from the FirstModule.
What is the expected behavior of provider resolution?
Package
- [ ] I don't know. Or some 3rd-party package
- [X]
@nestjs/common - [ ]
@nestjs/core - [ ]
@nestjs/microservices - [ ]
@nestjs/platform-express - [ ]
@nestjs/platform-fastify - [ ]
@nestjs/platform-socket.io - [ ]
@nestjs/platform-ws - [ ]
@nestjs/testing - [ ]
@nestjs/websockets - [ ] Other (see below)
Other package
No response
NestJS version
10
Packages versions
"dependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/platform-express": "^10.0.0",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1"
},
"devDependencies": {
"@nestjs/testing": "^10.0.0",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.1.3",
"vite": "5.2.9",
"vitest": "1.5.0"
},
Node.js version
20
In which operating systems have you tested?
- [ ] macOS
- [ ] Windows
- [X] Linux
Other
No response
By the way, you don't even export any providers from FirstModule. It seems that the problem is only observed in your tests. In the real application, everything works as you would expect:
import { NestFactory } from '@nestjs/core';
import { Controller, Get, Inject, Module } from '@nestjs/common';
const tokenSymbol = Symbol('Some-Token');
@Module({
providers: [{ provide: tokenSymbol, useValue: 'Batman' }],
exports: [tokenSymbol],
})
class FirstModule {}
@Controller()
export class FirstController {
constructor(@Inject(tokenSymbol) private batmanOrRobin: string) {}
@Get()
getHello(): string {
return this.batmanOrRobin;
}
}
@Module({
imports: [FirstModule],
providers: [{ provide: tokenSymbol, useValue: 'Robin' }],
controllers: [FirstController],
})
class SecondModule {}
@Module({
imports: [SecondModule],
})
export class AppModule {}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
By the way, you don't even export any providers from
FirstModule. It seems that the problem is only observed in your tests. In the real application, everything works as you would expect:import { NestFactory } from '@nestjs/core'; import { Controller, Get, Inject, Module } from '@nestjs/common'; const tokenSymbol = Symbol('Some-Token'); @Module({ providers: [{ provide: tokenSymbol, useValue: 'Batman' }], exports: [tokenSymbol], }) class FirstModule {} @Controller() export class FirstController { constructor(@Inject(tokenSymbol) private batmanOrRobin: string) {} @Get() getHello(): string { return this.batmanOrRobin; } } @Module({ imports: [FirstModule], providers: [{ provide: tokenSymbol, useValue: 'Robin' }], controllers: [FirstController], }) class SecondModule {} @Module({ imports: [SecondModule], }) export class AppModule {} async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(3000); } bootstrap();
I have updated my test to use NestFactory.create and it's still failing.
I have pushed the changes I have done to : https://github.com/chandu/nest-override-modules
Speciafically, https://github.com/chandu/nest-override-modules/blob/main/src/override.spec.ts#L38
First of all, I agree with you that it's confusing, but it looks like I can understand why it happens. Try running the following code:
import { NestFactory } from '@nestjs/core';
import { Inject, Module } from '@nestjs/common';
const tokenSymbol = Symbol('Some-Token');
@Module({
providers: [{ provide: tokenSymbol, useValue: 'Batman' }],
exports: [tokenSymbol],
})
class FirstModule {}
@Module({
imports: [FirstModule],
providers: [{ provide: tokenSymbol, useValue: 'Robin' }],
})
class SecondModule {
constructor(@Inject(tokenSymbol) public batmanOrRobin: string) {}
}
async function bootstrap() {
const app = await NestFactory.create(SecondModule);
const value1 = app.get(tokenSymbol);
console.log('per application:', value1);
const value2 = app.get(SecondModule);
console.log('per module:', value2.batmanOrRobin);
}
bootstrap();
This code prints the following values to the console:
per application: Batman
per module: Robin
The app.get(tokenSymbol) method returns the application-level provider value. First, Nest at the application level adds a provider with tokenSymbol taking the value from the SecondModule (Robin), and then this value is replaced by the value that is written in the FirstModule (Batman).
So the value returned by the Nest DI container depends on the scope.
Thanks @KostyaTretyak . Yes, I have run a similar check and am able to verify the returned values. I think the root cause of my confusion is aroud how the NestApplication instance behaves w.r.t to the root module. What still surprises me is the app is able to resolve a provider from FirstModule even when it is not exported and the FirstModule is not used as a root module.
Finally was able to make the tests pass (used select method of the NestApplication to set a module context).
I assumed the NestFactory.create would simulate something similar to select method for the root module passed as arg automatically, but apparently not.
describe('Can override a provider imported via a module', () => {
it('should work', async () => {
@Module({
providers: [{ provide: tokenSymbol, useValue: 'Batman' }],
})
class FirstModule {}
@Module({
imports: [FirstModule],
providers: [
{
provide: tokenSymbol,
useFactory() {
return 'Robin';
},
},
],
exports: [tokenSymbol],
})
class SecondModule {}
let app: INestApplication | null = null;
try {
app = await NestFactory.create(SecondModule, {
logger: false,
});
const selectedApp = app.select(SecondModule);
const value = selectedApp.get(tokenSymbol, {
strict: true,
});
expect(value).toEqual('Robin');
} finally {
app?.close();
}
});
});