Nest encountered a dependency resolution issue with LogService (?, LogFormatProvider). The argument String at index [0] needs to be available within the AppModule context

Here is the structure of my app.module.ts file:

import { Module, HttpModule } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { join } from 'path';
import { LaunchService } from './launch/launch.service';
import { LaunchResolver } from './launch/launch.resolver';
import { LaunchModule } from './launch/launch.module';
import { LogService } from '@fmr-pr103625/nest-scaffold';

@Module({
  imports: [
    GraphQLModule.forRoot<ApolloDriverConfig>({
      driver: ApolloDriver,
      typePaths: ['./**/*.graphql'],
      definitions: { path: join(process.cwd(), 'src/graphql.ts') },
    }),
    HttpModule,
    LaunchModule,
  ],
  controllers: [AppController],
  providers: [AppService, LaunchService, LaunchResolver, LogService],
})
export class AppModule {}


The content of my app.service.ts file is as follows:
import { Injectable } from '@nestjs/common';
import { Logger, LogService } from '@fmr-pr103625/nest-scaffold';

@Injectable()
export class AppService {
  @Logger()
  private logger: LogService;
  getHello(): string {
    this.logger.error('Hello');
    return 'Hello World!';
  }
}


I am facing an error while trying to use the built-in logservice from another repository.

Nest can't resolve dependencies of the LogService (?, LogFormatProvider). Please make sure that the argument String at index [0] is available in the AppModule context.

Potential solutions:
- If String is a provider, ensure it is part of the current AppModule.
- If String is exported from a separate @Module, ensure that module is imported within AppModule.
  @Module({
    imports: [ /* import the Module containing String */ ]
  })

---------------------------**********************---------------------------------

Let me know what I might have missed and how I can resolve this issue. I am simply testing the LogService functionality.

--------------------------**********************-----------------------------------

The code for the Log Service is shown below:

Object.defineProperty(exports, "__esModule", { value: true });
exports.LogService = void 0;

// The implementation details are provided here...

exports.LogService = LogService;

---------------------------*************************-------------------------------

Answer №1

The error message Nest cannot find dependencies for LogService (?, LogFormatProvider). indicates that a string value is needed in the constructor of the LogService as its first argument, specifically the category. This lack of knowledge during the injection process results in the error. While it's best to avoid such constructor design, if necessary, you can provide a default value. As an Architect/Tech Lead, I often advise simplifying the signature using application configuration values.

To identify the root cause within a unit testing environment, create a test scenario to help resolve the issue. Set up a testingModule to facilitate injection support:

testingModule = await Test.createTestingModule({
  imports: [...],
  providers: [LogService]
}).compile();

logService = testingModule.get(LogService);

If the injector needs clarification on what to provide for the category argument, utilize the @Inject() decorator. Add @Inject('LOG_CATEGORY') before the category argument in the constructor to specify the desired value ('LOG_CATEGORY') upon instantiation of the LogService.

constructor(@Inject('LOG_CATEGORY') category: string, ...) {...}

Update the testingModule to include the desired value. In the providers array, define a provider with the specified value (e.g., "Default" for category):

testingModule = await Test.createTestingModule({
  imports: [...],
  providers: [
    LogService,
    {
      provide: 'LOG_CATEGORY',
      useValue: 'Default'
    }
  ]
}).compile();

logService = testingModule.get(LogService);

The approach to addressing the issue may vary, but I hope this example provides insight into resolving it, particularly in a unit test setting. :D

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

Record data from identical code to separate locations

I have a situation where I have a class that logs information and is used in two different locations. class SomeClass: ISomeClass { private ILogger _logger = Log.GetLogger(); public void Action() { _logger.Log("Action started"); // ...

employing constructor objects within classes

I am attempting to utilize a class with a constructor object inside another class. How should I properly invoke this class? For example, how can I use Class 1 within Class 2? Below is an instance where an object is being created from a response obtained f ...

The functionality of React setState seems to be malfunctioning when activated

Having encountered an unusual issue with react's setState() method. Currently, I am utilizing Azure DevOps extensions components and have a panel with an onClick event that is intended to change the state of IsUserAddedOrUpdated and trigger the addOr ...

Managing image elements as attributes in React using styled-components

In my React project, I am working towards eliminating the use of .css files. Currently, I am refactoring existing .css code to utilize styled-components in a Typescript React project. Previously, images were included as backgrounds in a .css class a.item. ...

Strange behavior detected in TypeScript generic function when using a class as the generic parameter

class Class { } const f0 = <T extends typeof Class> (c:T): T => { return c } const call0 = f0 (Class) //ok const f1 = <T extends typeof Class> (c:T): T => { const a = new c() return a //TS2322: Type 'Class' is not assigna ...

Book of Tales displaying Emotion Styling upon initial load only

I'm currently working with the styled api provided by emotion in order to create a custom styled button. const StyledButton = styled(Button)` background-color: ${theme.palette.grey['800']}; width: 50; height: 50; &:hover { ba ...

Trouble with displaying points in Angular2's highcharts

I have implemented the angular2-highcharts chart module in my angular2 web application. Everything works fine when the graph has less than 7000 points, with the line and points displaying correctly. However, once the number of points surpasses 7000, there ...

Creating layers of object declarations

Looking for assistance on the code snippet below. type Item = { id: number; size: number; } type Example = { name: string; items: [ Item ]; } var obj: Example = { name: "test", items: [ { i ...

How to effectively merge DefaultTheme with styled-components in TypeScript?

I am facing an issue with integrating a module developed using styled-components that exports a theme. I want to merge this exported theme with the theme of my application. In my attempt in theme.ts, I have done the following: import { theme as idCheckThe ...

Generating Angular2 CLI components with Angular-Meteor integration

Exploring Angular2 CLI and Meteor has been an interesting journey for me. One thing I've noticed is that when I create a component using Angular2 CLI, integrating it into another module is as simple as including it in the declarations array of that mo ...

What is the best way to save the output of the services function as an array of objects in a separate TypeScript file?

I need to store the result of a function in my services into an array of objects in my TypeScript file. getserver(id:number) { const server = this.servers.find( (s) => { return s.id === id; } ) } The return type of this fu ...

Tips for handling delayed HTTP API responses in Angular

While working on my project, I encountered a delay in response when using the this.ServiceHandler.getTxnInfo([], params) API. To handle this, I implemented the use of setTimeout along with async/await. Despite these modifications, my promise ended up being ...

Typescript struggles to comprehend the nullish-coalescing operator

Within my Vue + TypeScript application, I've incorporated an external package called @moj/pagination-layout. This package utilizes the nullish operator internally. However, when attempting to run the build process, it encounters a failure and presents ...

Bring in exclusively typescript module declarations

In my various React projects, I find myself constantly declaring the same typescript modules, such as fonts.d.ts: declare module "*.woff"; declare module "*.woff2"; or images.d.ts: declare module "*.jpg" { const src: string ...

Getting access to a function within the same TypeScript file from another exported function in Angular

I'm having trouble accessing a function from another export function within the same TypeScript file. Can anyone help me with this? app.component.ts: import { Component } from '@angular/core'; @Component({ selector: 'app-root', ...

Navigating between two components eliminates the need for ongoing subscriptions within the NGRX store

In my application, I have two main pages named Dashboard and Transactions, along with a component called Sidebar responsible for navigation control. The initial transition from the Dashboard to the Transactions page involves subscribing to the user state ...

How can you activate or deactivate Bootstrap Checkboxes using buttons in Angular 9?

I've been working on developing a page in Angular, although I'm still getting the hang of it. Despite spending several hours and going through numerous threads trying to find a solution, I haven't been able to address my specific issue. Jus ...

Issue: "Stumbled upon an unknown provider! This often implies the presence of circular dependencies"

Looking for help on a perplexing error in my Angular / TypeScript app. While we wait for an improved error message, what steps can we take to address this issue? What are the potential triggers for this error to occur? Uncaught Error: Encountered undefi ...

Several cucumber reports are showing an error message containing special characters

I am encountering an issue in the multiple cucumber report where error messages are being displayed with special characters. Is there a way to format them properly? I am currently learning Playwright, Typescript, and CucumberJs and generating reports for m ...

Retrieve intricate information from an API, generate an array of objects, and loop through them

I am attempting to create an array of intricate objects from the following data: My goal is to utilize this object array to generate components using map() To structure the response type, I utilized : // ... other types like Tag export type DatasetInfo ...