NestJS test cannot resolve PinoLogger dependency - node.js

On NestJS application startup I am creating few db tables (using TypeORM) and have written service file init-db.service.ts for the same. The service file implements OnApplicationBootstrap interface and onApplicationBootstrap method is called once the application has fully started and is bootstrapped.
I am trying to write a unit test for the service file, but is unable to resolve PinoLogger dependency while creating Testing Module. Please checkout below sample code:
Service file init-db.service.ts:
import {ConfigService} from '#nestjs/config';
import {PinoLogger} from 'nestjs-pino';
import {Injectable, OnApplicationBootstrap} from '#nestjs/common';
#Injectable()
export class InitDB implements OnApplicationBootstrap {
constructor(private readonly logger: PinoLogger, private readonly configService: ConfigService) {}
onApplicationBootstrap() {
this.someMethod();
}
async someMethod(): Promise<void> {
// code to create tables...
}
}
Unit test file init-db.service.spec.ts:
import {ConfigService} from '#nestjs/config';
import {Test, TestingModule} from '#nestjs/testing';
import {InitDB} from './init-db.service';
import {getLoggerToken, PinoLogger} from 'nestjs-pino';
const mockLogger = {
// mock logger functions
};
describe('InitDB', () => {
jest.useFakeTimers();
let configService: ConfigService;
let service: InitDB;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
{
provide: getLoggerToken(InitDB.name), // <-------- PinoLogger dependency
useValue: mockLogger,
},
InitDB,
ConfigService,
],
}).compile();
service = module.get<InitDB>(InitDB);
configService = module.get<ConfigService>(ConfigService);
});
afterEach(() => {
jest.clearAllMocks();
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
Error Message:
Nest can't resolve dependencies of the BootstrapService (?, ConfigService). Please make sure that the argument PinoLogger at index [0] is available in the RootTestModule context.
Potential solutions:
- If PinoLogger is a provider, is it part of the current RootTestModule?
- If PinoLogger is exported from a separate #Module, is that module imported within RootTestModule?
#Module({
imports: [ /* the Module containing PinoLogger */ ]
})
I have already passed PinoLogger at index [0], but the unit test still fails to resolve the dependency.

Please note that you don't use #InjectPinoLogger but you are trying to mock it as if you have used it.
You could either provide PinoLogger as a dependency:
const module: TestingModule = await Test.createTestingModule({
providers: [
PinoLogger,
InitDB,
ConfigService,
],
}).compile();
or use #InjectPinoLogger in your class constructor:
export class InitDB implements OnApplicationBootstrap {
constructor(
#InjectPinoLogger(InitDB.name)
private readonly logger: PinoLogger,
private readonly configService: ConfigService
) {}
}

Related

NestJS Jest error: TypeError: Cannot read properties of undefined (reading '[any variable from required config]')

While trying to cover out project in unit tests using nest's jest I've bumped into a problem of a testing module not being able to pull variables from config.
Basically, I have an EmailService, I want to test it, I use it as a Provider in my testing module. Naturally, as EmailService takes ConfigService in its constructor to pull some variables from config (that initially come from env) I put ConfigService into the providers array as well... well, then upon initialization testing module drops
NestJS Jest error: TypeError: Cannot read properties of undefined (reading 'region')
note: region variable is taken from env in a registered config module
code example of my test that throws
describe('EmailService', () => {
let emailService: EmailService;
let configService: ConfigService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [EmailService, ConfigService],
}).compile();
emailService = module.get<EmailService>(EmailService);
configService = module.get<ConfigService>(ConfigService);
});
it('should be defined', () => {
expect(emailService).toBeDefined();
});
});
I have came to the conclusion that it throws an error specifically because EmailService takes ConfigService in it's constructor in this way:
export class EmailService {
private readonly config: IAwsConfig;
private readonly region: IRegion;
constructor(private readonly configService: ConfigService) {
this.config = this.configService.get('aws');
this.region = this.config.region;
}
aditional info: both EmailService and ConfigService work just fine during a normal runtime, it only fails during jest testing
seems like this.configService.get method returns 'undefined' during a test run and i'm, not sure why or how to fix it. Any ideas?
In case you don't want to import the entire ConfigService but just the config values themselves, then you use them in the test as follows :)
// my-config.ts
import { registerAs } from '#nestjs/config';
export default registerAs('myConfig', () => ({ propA: 'aa', propB: 123 }));
import { Inject } from '#nestjs/common';
import { ConfigType } from '#nestjs/config';
import myConfig from './my-config.ts';
export class EmailService {
private propA: string;
private propB: number;
constructor(
#Inject(myConfig.KEY) config: ConfigType<typeof myConfig>
) {
this.propA = config.propA;
this.propB = config.propB;
}
}
import { ConfigModule, registerAs } from '#nestjs/config';
import { Test, TestingModule } from '#nestjs/testing';
describe('Test', () => {
const configValues = { propA: 'aa', proprB: 123 };
const config = registerAs('testConfig', () => configValues);
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
imports: [ConfigModule.forFeature(config)],
providers: [EmailService],
}).compile();
});
});
Was not able to find an answer for 2 hours straight, but then, 10 minutes after asking a question, there you go, an answer.
Seems like ConfigService doesn't provide configs during jest testing so you have to provide it in the testing module with replaced get method, something like such:
providers: [
EmailService,
{
provide: ConfigService,
useValue: {
get: jest.fn((key: string) => {
return hardcodedConfigFromWithinTheTestFile;
}),
},
},
],

Cannot inject custom provider for dynamic module

I tried to create a dynamic module PermissionModule like the following:
permTestApp.module.ts
#Module({
imports: [PermissionModule.forRoot({ text: 'abc' })],
providers: [],
controllers: [PermissionTestController],
})
export class PermissionTestAppModule {}
permission.module.ts
import { DynamicModule, Module } from '#nestjs/common'
import { PermissionGuard } from './guard/permission.guard'
#Module({})
export class PermissionModule {
public static forRoot(config: { text: string }): DynamicModule {
return {
module: PermissionModule,
providers: [
{
provide: 'xoxo',
useValue: config.text,
},
PermissionGuard,
],
exports: [PermissionGuard],
}
}
}
permission.guard.ts
import {
CanActivate,
ExecutionContext,
Inject,
Injectable,
} from '#nestjs/common'
#Injectable()
export class PermissionGuard implements CanActivate {
constructor(#Inject('xoxo') private readonly config: string) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
console.log(31, this.config)
return true
}
}
AFAIK, 'abc' string must be injected when PermissionGuard is used.
I tried to test it with the following code.
permission.e2e.spec.ts
beforeAll(async () => {
const moduleRef: TestingModule = await Test.createTestingModule({
imports: [PermissionTestAppModule],
})
.compile()
app = moduleRef.createNestApplication()
controller = await moduleRef.resolve(PermissionTestController)
await app.init()
})
but it says,
Nest can't resolve dependencies of the PermissionGuard (?). Please make sure that the argument xoxo at index [0] is available in the PermissionTestAppModule context.
Potential solutions:
- Is PermissionTestAppModule a valid NestJS module?
- If xoxo is a provider, is it part of the current PermissionTestAppModule?
- If xoxo is exported from a separate #Module, is that module imported within PermissionTestAppModule?
#Module({
imports: [ /* the Module containing xoxo */ ]
})
What am I doing wrong?

NestJS can't resolve dependencies of class that is provided with a factory

Let me introduce you the AlgoModule:
const apiFactory = {
provide: 'API',
useFactory: (moduleRef: ModuleRef, config: ConfigService) => {
const apiService: Type<IApi> = config.getApiService();
return moduleRef.get(apiService)
},
inject: [ModuleRef, ConfigService]
}
#Module({
imports: [ConfigModule],
providers: [
// Services
ApiService,
ApiTestService,
TestService,
// Factories
apiFactory
],
exports: []
})
export class AlgoModule {}
This module imports the ConfigModule and has a factory that creates an IApi instance which is either ApiService or ApiTestService based on env parameters that ConfigService under ConfigModule has loaded.
The factory uses the ConfigService injected onto it and the ModuleRef in order to create an instance of IApi.
This is an example of one of the implementations of IApi - ApiService:
#Injectable()
export class ApiService implements IApi {
constructor(private config: ConfigService) {
}
}
Now when I create a new service and put it in the provides of AlgoModule, let's say TestService:
#Injectable()
export class TestService {
constructor(
private config: ConfigService,
#Inject('API') private api: IApi) {
}
}
What I did here is, inject IApi with the token 'API' which is what I set up in AlgoModule using the apiFactory
I will get the following error upon start:
Error: Nest can't resolve dependencies of the ApiService(?). Please make sure that the argument dependency at index [0] is available in the AlgoModule context.
What did I do wrong?
I am wondering, because I imported the ConfigModule within AlgoModule so the factory should automatically have the dependencies of it.
ConfigService:
#Injectable()
export class ConfigService {
serviceMapping = {
prod: ApiService,
test: ApiTestService
};
getEnv(): string | 'prod' | 'test' {
return String(process.env.ENV);
}
getApiService(): Type<IApi> {
const env = this.getEnv();
return this.serviceMapping[env];
}
}
Did you call ConfigModule.forRoot with flag isGlobal somewhere in global modules?
If not then you must because ConfigModule does not work as you imagine.
ConfigModule.forRoot or forFeature exposes ConfigService token for module but plain ConfigModule do not unless it is global.

Nest.js is unable to resolve Mongoose model dependency in unit test

When writing a unit test for a controller, Nest is unable to resolve my Mongoose model dependency:
Nest can't resolve dependencies of the UsersService (?). Please make
sure that the argument USER_MODEL at index [0] is available in the
_RootTestModule context.
Potential solutions:
- If USER_MODEL is a provider, is it part of the current _RootTestModule?
- If USER_MODEL is exported from a separate #Module, is that module imported within _RootTestModule?
#Module({
imports: [ /* the Module containing USER_MODEL */ ]
})
My model is injected via my service constructor in the users.service.ts:
import { IUserModel } from './interfaces';
import { Model } from 'mongoose';
import { USER_MODEL } from './constants/users.constants';
#Injectable()
export class UsersService {
constructor (
#Inject(USER_MODEL)
private readonly userModel: Model<IUserModel>,
) {}
...
}
and my test is defined as:
const mockUserModel = {};
describe('Users Controller', () => {
let usersController: UsersController;
let usersService: UsersService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UsersController],
providers: [
{
provide: getModelToken(USER_MODEL),
useValue: mockUserModel,
},
UsersService,
],
}).compile();
usersController = module.get<UsersController>(UsersController);
usersService = module.get<UsersService>(UsersService);
});
it('should define user controller and service', () => {
expect(usersController).toBeDefined();
expect(usersService).toBeDefined();
});
});
All of these classes are defined in the same module. I'm not quite sure what Nest is looking for. I'm following the guide at: https://docs.nestjs.com/fundamentals/testing and have looked through several older Github issues as well.
I've also tried creating a custom class provider as defined here: https://docs.nestjs.com/fundamentals/custom-providers to supply the typed Mongoose Model, but that returned the same error.
Can anyone help me out?
If you are using #Inject(USER_MODEL) then you need to use provide: USER_MODEL in your test. The getModelToken utility method is necessary if you use #InjectModel() instead of the raw #Inject().

Nest can't resolve dependencies of the VendorsService (?). Please verify whether [0] argument is available in thecurrent context

I am new to nest js and typescript also. Thanks in advance.
I am getting this error continuously.
Nest can't resolve dependencies of the VendorsService (?). Please verify whether [0] argument is available in thecurrent context.
Here is the code
App module
#Module({
imports: [ UsersModule, VendorsModule],
})
export class ApplicationModule {}
controller
#Controller()
export class VendorsController {
constructor(private readonly vendorService: VendorsService){}
#Post()
async create(#Body() createVendorDTO: CreateVendorDTO){
this.vendorService.create(createVendorDTO);
}
#Get()
async findAll(): Promise<Vendor[]>{
return this.vendorService.findAll();
}
}
Service
#Injectable()
export class VendorsService {
constructor(#Inject('VendorModelToken') private readonly vendorModel: Model<Vendor>) {}
async create(createVendorDTO: CreateVendorDTO): Promise<Vendor>{
const createdVendor = new this.vendorModel(createVendorDTO);
return await createdVendor.save();
}
async findAll(): Promise<Vendor[]>{
return await this.vendorModel.find().exec();
}
}
provider
export const usersProviders = [
{
provide: 'VendorModelToken',
useFactory: (connection: Connection) => connection.model('Vendor', VendorSchema),
inject: ['DbConnectionToken'],
},
];
Module
#Module({
providers: [VendorsService],
controllers: [VendorsController],
})
export class VendorsModule {}
VendorsModule sould declare your provider (usersProviders) in its providers, otherwise Nestjs will never be able to inject it into your service.
Unless you wanted to declare it with UsersModule (I guess you did); in that case, UsersModule also needs it in its exports so it's made visible to other modules importing UsersModule.
It's either VendorsModule: usersProviders in providers,
Or UsersModule: usersProviders in both providers and exports

Resources