Testing a NestJS service with multiple constructor parameters can be done by utilizing various techniques such as dependency

Content

When testing a service that needs one parameter in the constructor, it's essential to initialize the service as a provider using an object instead of directly passing the service through:

auth.service.ts (example)

@Injectable()
export class AuthService {

  constructor(
    @InjectRepository(Admin)
    private readonly adminRepository: Repository<Admin>,
  ) { }

  // ...

}

auth.service.spec.ts (example)

describe('AuthService', () => {
  let authService: AuthService


  beforeEach(async () => {
    const module = await Test.createTestingModule({
        providers: [
          AuthService,
          {
            provide: getRepositoryToken(Admin),
            useValue: mockRepository,
          },
        ],
      }).compile()

    authService = module.get<AuthService>(AuthService)
  })

  // ...

})

For more information on this topic, refer to this GitHub issue.


Current Challenge

In my case, the service requires two parameters in the constructor:

auth.service.ts

@Injectable()
export class AuthService {
  constructor(
    private readonly jwtService: JwtService,
    private readonly authHelper: AuthHelper,
  ) {}

  // ...

}

How do I initialize this service in the test environment? Since passing multiple values to useValue in the providers array is not straightforward, how can I handle this situation? The AuthService constructor expects two parameters, and both need to be provided for successful testing.

This is the current (non-working) setup:

auth.service.spec.ts

describe('AuthService', () => {
  let service: AuthService

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [AuthService],
    }).compile()

    service = module.get<AuthService>(AuthService)
  })

  it('should be defined', () => {
    expect(service).toBeDefined()
  })

  // ...

})

If the parameters are not passed, the following error occurs:

  ● AuthService › should be defined

    Nest can't resolve dependencies of the AuthService (?, AuthHelper). Please ensure that the argument at index [0] is available in the TestModule context.

Answer №1

To easily add new dependencies to your AuthService, simply insert them into the providers array in the constructor:

beforeEach(async () => {
  const module: TestingModule = await Test.createTestingModule({
    providers: [
      AuthService,
      {provide: DatabaseService, useValue: databaseServiceMock},
      {provide: LoggerService, useValue: loggerServiceMock},
    ],
  }).compile()

When using the utility method Test.createTestingModule(), a module similar to AppModule is created with its own providers array for handling dependency injection.

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

What is the reason for node executing both of these handlers on the server?

My node app is set up with two handlers, one for requests to the root URL and another for the slug. However, when I visit the root or slug URLs, the app crashes and I receive this error: url is pointing to root url has a slug throw err; // Rethrow non-MySQ ...

Error in Nestjs Swagger: UnhandledPromiseRejectionWarning - The property `prototype` cannot be destructed from an 'undefined' or 'null' object

Currently, I am in the process of developing a Nestjs REST API project and need to integrate swagger. For reference, I followed this repository: https://github.com/nestjs/nest/tree/master/sample/11-swagger However, during the setup, I encountered the foll ...

Guide to importing a JSON file in a Node.js JavaScript file

I am trying to incorporate a JSON file into my JavaScript code in a Node.js application. I attempted to include it using the "require();" method, but encountered an issue: "Uncaught ReferenceError: require is not defined". ...

When the disk space is insufficient, the createWriteStream function will not trigger an error event if the file is not completely written

One challenge I'm encountering involves using createWriteStream: Imagine I have a large 100mb file that I want to write to another file on the disk. The available space on the disk is only 50mb. Here's my code snippet: const fs = require(&a ...

Can you explain the concept of F-Bounded Polymorphism in TypeScript?

Version 1.8 of TypeScript caught my attention because it now supports F-Bounded Polymorphism. Can you help me understand what this feature is in simple terms and how it can be beneficial? I assume that its early inclusion signifies its significance. ...

What was the reason for node js not functioning properly on identical paths?

When the search route is placed at the top, everything works fine. However, when it is placed at the end, the route that takes ID as a parameter keeps getting called repeatedly in Node. Why does this happen and how can it be resolved? router.get('/se ...

The absence of essential DOM types in a TypeScript project is causing issues

Recently, I've been working on setting up a web app in TypeScript but I seem to be missing some essential types that are required. Every time I compile using npm run build, it keeps throwing errors like: Error TS2304: Cannot find name 'HTMLEleme ...

Is it possible to integrate Wavify with React for a seamless user experience?

For my website designs, I have been experimenting with a JavaScript library known as Wavify (https://github.com/peacepostman/wavify) to incorporate wave animations. Recently delving into the world of React, I pondered whether I could integrate Wavify into ...

Error: Property 'config' cannot be accessed because it is null

Upon transferring my Angular project from my local computer to a Linux server, I attempted to launch the project using ng serve but encountered an issue where it opened a new file in the console editor instead. After some investigation, I tried running np ...

Is there a way to reverse a string in Javascript without using any built-in functions?

I am looking for a way to reverse a string without using built-in functions like split, reverse, and join. I came across this code snippet on Stack Overflow (), but I'm having trouble understanding what the code does on the fourth line. I need more cl ...

Step-by-step guide for launching a Next.js/Node application

Currently, I am developing a full-stack project utilizing a next.js application for the front-end and a node/express server for the API. The front-end and back-end are running on separate ports. Here is how my application is configured: https://i.stack.im ...

Best Practices for Safely Storing the JWT Client Credentials Grant

Currently, I am working on a NodeJS Express Application that connects to an Auth Server using client credentials grant. After receiving the token from the Auth Server, I use it to access data from an API. I am seeking advice on the most effective way to s ...

How can Node.js and Express be used to conceal Javascript code on the backend?

I'm a beginner when it comes to Node and Express. I have a query regarding how to securely hide Javascript code on the backend. Currently, I am working with Node.js and Express. My goal is to prevent users from easily accessing the code through browse ...

Escape a "for" loop from within a callback function in Node.js

My objective with the code snippet below is to exit FOR LOOP B and continue with FOR LOOP A by utilizing a callback function. for(var a of arrA) { // ... // ... for(var b of arrB) { // ... // ... PartService.getPart(a ...

Angular 2 encountering an error with the HTTP GET request

I am currently facing some challenges with subscribing to the response while using the http method get request. Below is my service implementation: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http&ap ...

What is the process for configuring environmental variables within my client-side code?

Is there a reliable method to set a different key based on whether we are in development or production environments when working with client-side programs that lack an inherent runtime environment? Appreciate any suggestions! ...

I will evaluate two arrays of objects based on two distinct keys and then create a nested object that includes both parent and child elements

I'm currently facing an issue with comparing 2 arrays of objects and I couldn't find a suitable method in the lodash documentation. The challenge lies in comparing objects using different keys. private parentArray: {}[] = [ { Id: 1, Name: &ap ...

Building a Next.js application that supports both Javascript and Typescript

I currently have a Next.js app that is written in Javascript, but I am looking to transition to writing new code in Typescript. To add Typescript to my project, I tried creating a tsconfig.json file at the project root and then ran npm install --save-dev ...

When using the e.target.getAttribute() method in React, custom attributes may not be successfully retrieved

I am struggling with handling custom attributes in my changeHandler function. Unfortunately, React does not seem to acknowledge the custom "data-index" attribute. All other standard attributes (such as name, label, etc.) work fine. What could be the issu ...

Managing absence of ID field in Prisma and retrieving data from API request

When fetching data from an API, my approach looks like this: async function getApiData() { const promises = []; for (let i = 0; i < PAGE_COUNT; i++) { const apiData = fetch(...); } const apiData = await Promise.all(promises); return apiDat ...