Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJs Testing with CACHE_MANAGER injected

I have some service in which I inject the CACHE_MANAGER in the constructor

import { CACHE_MANAGER, Inject, Injectable } from '@nestjs/common';
import { Cache } from 'cache-manager';
...
export class ManagerService {
   constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
   ...
}

That gives me an error when I test the modules the import those service

Nest can't resolve dependencies of the ManagerService (?). Please make sure that the argument CACHE_MANAGER at index [0] is available in the Web3ManagerService context.

I'm relatively new to NestJs so I really cannot figure out how to solve it

like image 544
mpalma Avatar asked May 06 '26 10:05

mpalma


2 Answers

I just had the same problem and resolved it this way:

manager.service.spec.ts

beforeEach(async () => {
  const module: TestingModule = await Test.createTestingModule({
    providers: [ManagerService, { provide: CACHE_MANAGER, useValue: {} }],
  }).compile();

  service = module.get<ManagerService>(ManagerService);
});
like image 188
Michal Pidanič Avatar answered May 08 '26 22:05

Michal Pidanič


To inject the cache manager provider under the CACHE_MANAGER, you need to import the nestjs module that creates this provider into the module that has the ManagerService

@Module({
  imports: [CacheModule.register()], // <<<<
  providers: [ManagerService],
})
export class AppModule {}

like the docs shows https://docs.nestjs.com/techniques/caching

like image 24
Micael Levi Avatar answered May 09 '26 00:05

Micael Levi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!