The testString's dependencies are unresolved by Nest

Encountered Problem:
Facing the following issue while running a unit test case

Nest is unable to resolve the dependencies of the testString (?). Please ensure that the argument SECRET_MANAGER_SERVICE at index [0] is available in the context of SecretManagerServiceModule.


Error Logs:
SecretsManagerServiceModule › #forFeature() › Should have plain string secret (without id)

Nest is unable to resolve the dependencies of the testString (?). Please ensure that the argument SECRET_MANAGER_SERVICE at index [0] is available in the context of SecretManagerServiceModule.

Possible solutions:
- If SECRET_MANAGER_SERVICE is a provider, is it part of the current SecretManagerServiceModule?
- If SECRET_MANAGER_SERVICE is exported from a separate @Module, is that module imported within SecretManagerServiceModule?
  @Module({
    imports: [ /* the Module containing SECRET_MANAGER_SERVICE */ ]
  })

  at Injector.lookupComponentInParentModules (node_modules/@nestjs/core/injector/injector.js:190:19)
  at Injector.resolveComponentInstance (node_modules/@nestjs/core/injector/injector.js:146:33)
  at resolveParam (node_modules/@nestjs/core/injector/injector.js:100:38)
      at async Promise.all (index 0)
  at Injector.resolveConstructorParams (node_modules/@nestjs/core/injector/injector.js:115:27)
  at Injector.loadInstance (node_modules/@nestjs/core/injector/injector.js:79:9)
  at Injector.loadProvider (node_modules/@nestjs/core/injector/injector.js:36:9)
      at async Promise.all (index 3)
  at InstanceLoader.createInstancesOfProviders (node_modules/@nestjs/core/injector/instance-loader.js:41:9)
  at node_modules/@nestjs/core/injector/instance-loader.js:27:13


Code Snippet:

Github Link: https://github.com/bhushan629/aws

test('Should have plain string secret (without id)', async () => {
      const response: AWS.SecretsManager.GetSecretValueResponse = {
        SecretString: 'hello',
      };

      AWSMock.mock('SecretsManager', 'getSecretValue', Promise.resolve(response));
      const module: TestingModule = await Test.createTestingModule({
        imports: [
          SecretManagerServiceModule.forRoot({}),
          SecretManagerServiceModule.forFeature({
            confiiguration: [{ secretName: 'testString', secretType: 'plain' }],
          }),
        ],
      }).compile();
      const plainString = module.get('testString');
      expect(plainString).toEqual('hello');
    });


I have attempted to emulate the structure of nestjs/mongoose (https://github.com/nestjs/mongoose) but I am facing issues. Does anyone know what could be wrong with this code?

How to Implement:


app.module.ts : This will initialize SecretsManager

@Module({
  imports: [SecretManagerServiceModule.forRoot({})],
})
class AppModule {}


sample.module.ts : once secrets manager is initialized, we can use the forFeature function to inject secrets into any providers

@Module({
  imports: [
    SecretManagerServiceModule.forFeature({
      confiiguration: [{ secretName: 'testString', secretType: 'plain' }],
    }),
  ],
  providers: [SampleService],
})
class SampleModule {}


sample.service.ts

@Injectable()
class SampleService {
  constructor(@Inject('testString') testStr: string) {}
}


Answer №1

Revised on 01/06/2020

Upon reviewing the code and the conversation held on discord (jmcdo29), the solution emerged as marking the SecretManagerServiceModule with @Global(). By doing so, after executing

SecretManagerServiceModule.forRoot()
, the provider remains accessible when running
SecretManagerServiceModule.forFeature()
.

Consider creating a core module similar to how NestJS organizes Mongoose and TypeORM, for the purpose of maintaining cleaner and more understandable code structure. It's great that you were able to resolve the issue :)


Based on the provided code snippet, it appears that you are attempting to inject a value associated with the injection token testString. Without visibility into the tokens defined in your modules, it is essential to ensure that either your forRoot or forFeature method includes something like this in the providers array:

{
  provide: 'testString',
  useValue: theValueYouWantToInject
}

If additional assistance is needed, more code context would be required. Specifically, insights into how your SecretsManagerModule functions within forRoot and forFeature methods, as well as the injection tokens being utilized.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

You may encounter an error stating "Property X does not exist on type 'Vue'" when attempting to access somePropOrMethod on this.$parent or this.$root in your code

When using VueJS with TypeScript, trying to access a property or method using this.$parent.somePropOrMethod or this.$root.somePropOrMethod can lead to a type error stating that Property somePropOrMethod does not exist on type 'Vue' The defined i ...

"Typescript: Unraveling the Depths of Nested

Having trouble looping through nested arrays in a function that returns a statement. selectInputFilter(enteredText, filter) { if (this.searchType === 3) { return (enteredText['actors'][0]['surname'].toLocaleLowerCase().ind ...

What might be causing my action function to be triggered during the rendering process?

While working on creating a basic card view in material UI, I encountered an issue where the functions for adding and deleting items seem to be triggered multiple times upon rendering. I am aware that a common reason for this could be using action={myFunc ...

Using Jasmine to simulate an if/else statement in Angular/Typescript unit testing

After making a minor change to an existing function, it has been flagged as new code during our quality checks. This means I need to create a unit test specifically for the new 4 lines of code. The challenge is that there was never a unit test in place for ...

How can one pass a generic tuple as an argument and then return a generic that holds the specific types within the tuple?

With typescript 4 now released, I was hoping things would be easier but I still haven't figured out how to achieve this. My goal is to create a function that accepts a tuple containing a specific Generic and returns a Generic containing the values. i ...

The Angular service is sending back the error message "undefined" when trying to retrieve data with the ID parameter from the requested

When calling a service from a component, I am encountering a 400 bad request error with the following message: "Invalid data 'undefined' for parameter id" It's worth noting that the getProduct method in the API is functioning correctly. ...

Using ES6 import with the 'request' npm module: A Step-by-Step Guide

When updating TypeScript code to ES6 (which runs in the browser and Node server, with a goal of tree-shaking the browser bundle), I am attempting to replace all instances of require with import. However, I encountered an issue... import * as request from ...

Using TypeScript to filter and compare two arrays based on a specific condition

Can someone help me with filtering certain attributes using another array? If a condition is met, I would like to return other attributes. Here's an example: Array1 = [{offenceCode: 'JLN14', offenceDesc:'Speeding'}] Array2 = [{id ...

Should ts-node be avoided in a production environment due to potential risks?

My current setup involves using ts-node with express in production and so far, it's been functioning smoothly. Am I missing out on any benefits by not compiling and running .js files instead? ...

Pass on only the necessary attributes to the component

I have a simple component that I want to include most, if not all, of the default HTML element props. My idea was to possibly extend React.HTMLAttributes<HTMLElement> and then spread them in the component's attributes. However, the props' ...

Combine the object with TypeScript

Within my Angular application, the data is structured as follows: forEachArrayOne = [ { id: 1, name: "userOne" }, { id: 2, name: "userTwo" }, { id: 3, name: "userThree" } ] forEachArrayTwo = [ { id: 1, name: "userFour" }, { id: ...

Having trouble with subscribing to a template in Ionic framework

I'm attempting to showcase an image from Firebase storage using the following code: Inside my component : findImg(img) { this.storage.ref('/img/' + img).getDownloadURL().subscribe( result => { console.log(result); ...

Dynamically modifying the display format of the Angular Material 2 DatePicker

I am currently utilizing Angular 2 Material's DatePicker component here, and I am interested in dynamically setting the display format such as YYYY-MM-DD or DD-MM-YYYY, among others. While there is a method to globally extend this by overriding the " ...

Issue with debugging Azure Functions TypeScript using f5 functionality is unresolved

I am encountering issues running my Azure TypeScript function locally in VS code. I am receiving the errors shown in the following image. Can someone please assist me with this? https://i.stack.imgur.com/s3xxG.png ...

Revamping HTML with AngularJS Directive: Enhancing the Layout with New Angular Attributes

I am currently facing an issue with the compiler not recognizing a new attribute I have added in a directive. In my Angular TypeScript code, I have the following setup: public class MyDirectiveScope: ng.IScope { foo: boolean; } public class MyDirecti ...

Executing methods sequentially in the ngOnInit lifecycle hook consecutively

Working with Angular15 has presented me with a challenge. In my app.component.ts file, I have two methods: “ngOnInit()”, as shown below. public ngOnInit(): void { this.getToken(); this.UserLoggedIn(); } I am looking to run the above two functions in ...

Creating a TypeScript function that can dynamically assign values to a range of cells within a column, such as AD1, AD2, AD3, and so on

Hello there I'm currently working on a function that will dynamically assign values to the column range of AE to "AD" + i. However, when I use the function provided below, it only writes AD5 into the first 5 columns instead of AD1, AD2, AD3, and so o ...

"Exploring the process of making a REST call from an Angular TypeScript client to

I'm currently developing a Sessions Server for a project at work. My dilemma lies in the fact that I'm struggling to find resources on how to make JavaScript HTTP calls from a server running with http.createServer() and server.listen(8080, ...) ...

Undefined TypeScript Interface

Here's my situation: public retrieveConnections() : IUser[] { let connections: IUser[]; connections[0].Id = "test"; connections[0].Email = "asdasd"; return connections; } I know this might be a dumb question, but why is connecti ...

Creating synchronous behavior using promises in Javascript

Currently, I am working with Ionic2/Typescript and facing an issue regarding synchronization of two Promises. I need both Promises to complete before proceeding further in a synchronous manner. To achieve this, I have placed the calls to these functions in ...