NestJS testing issue encountered: Compiled JS file not found in E2E test using Mocha

I'm currently facing an issue with executing an E2E test. The file structure for the E2E test is auto-generated by nestcli.

import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';

describe('AppController (e2e)', () => {
  let app: INestApplication;

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it('/ (GET)', () => {
    return request(app.getHttpServer())
      .get('/')
      .expect(200)
      .expect('test');
  });
});

The tests are running using mocha, and my package.json test script command is:

"test": "mocha --exit --require ts-node/register test/**/*.spec.ts test/*.spec.ts"

The error message I'm encountering is:

 1) AppController (e2e)
       "before each" hook for "/ (GET)":
     Error: File <root_path>/src/queuemanager/status.processor.js does not exist
      at Queue.setHandler (node_modules/bull/lib/queue.js:641:13)
      at Queue.process (node_modules/bull/lib/queue.js:610:8)
      at option.processors.forEach (node_modules/@nestjs/bull/dist/bull.providers.js:27:27)
      at Array.forEach (<anonymous>)
      at buildQueue (node_modules/@nestjs/bull/dist/bull.providers.js:12:27)
      at InstanceWrapper.useFactory [as metatype] (node_modules/@nestjs/bull/dist/bull.providers.js:57:20)
      at Injector.instantiateClass (node_modules/@nestjs/core/injector/injector.js:289:55)
      at callback (node_modules/@nestjs/core/injector/injector.js:42:41)

The project directory structure in src is as follows:

 $ tree -L 2
.
├── app.controller.ts
├── app.module.ts
├── app.service.ts
├── main.ts
└── queuemanager
    ├── queuemanager.controller.ts
    ├── queuemanager.module.ts
    └── status.processor.ts

This setup closely resembles the example provided in https://github.com/nestjs/nest/tree/master/sample/26-queues. Essentially, a queue is created using status.processor.ts to process tasks in a separate process. The queuemanager module appears like this:

import { Module } from '@nestjs/common';
import { BullModule } from '@nestjs/bull';
import { QueuemanagerController } from './queuemanager.controller';
import { join } from 'path';

@Module({
  imports: [
    BullModule.registerQueue({
          name: 'status',
          processors: [{
            name: 'statusProcessing',
            path: join(__dirname, 'status.processor.js')
          }]
        }),
  ],
  controllers: [QueuemanagerController],
})
export class QueuemanagerModule {}

To resolve this issue, I need to provide the compiled path to the js file. However, it seems like the test is unable to locate it correctly — possibly due to compilation errors. Any assistance on this matter would be greatly appreciated. Thank you

Answer №1

Maybe this solution will work for you, I can't be sure but here is what I did:

import { Module } from '@nestjs/common';
import { BullModule } from '@nestjs/bull';
import { QueuemanagerController } from './queuemanager.controller';
import { join } from 'path';

const filename: string = process.env.NODE_ENV === 'test' ? 'status.processor.ts' : 'status.processor.js';

@Module({
  imports: [
    BullModule.registerQueue({
          name: 'status',
          processors: [{
            name: 'statusProcessing',
            path: join(__dirname, filename)
          }]
        }),
  ],
  controllers: [QueuemanagerController],
})
export class QueuemanagerModule {}

You need to add NODE_ENV=test in the npm script that runs the test. If there's a better way, please let me know.

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

The type 'string' cannot be assigned to type 'ImageSourcePropType'

Context Attempting to utilize a SVG component in React Native with the xlinkHref property within an Image tag. The SVG file was converted into a React Native Component (TSX) using the tool provided at . While simple SVG icons have been successfully used be ...

Failed to retrieve values from array following the addition of a new element

Does anyone have a solution for this problem? I recently added an element to my array using the push function, but when I tried to access the element at position 3, it wasn't defined properly processInput(inputValue: any): void { this.numOfIma ...

Error encountered when attempting to utilize ngTemplate to embed filter within a table

I am facing an issue with a component that includes a primeng table. Within a table row, I have an ng-container to project a p-columnFilter into the table from an external source. However, when trying to pass the filter into the template, I encounter a Nul ...

Angular2 Interactive Modal Pop Up

Here is an example of a modal in HTML code: <app-modal #modal1> <div class="app-modal-header"> header </div> <div class="app-modal-body"> You c ...

Is there a way to deactivate a tab when it's active and reactivate it upon clicking another tab in Angular?

<a class="nav-link" routerLink="/books" routerLinkActive="active (click)="bookTabIsClicked()" > Books </a> I am currently teaching myself Angular. I need help with disabling this tab when it is active ...

Navigating Routes with Router in Angular 7: A Step-by-Step Guide

Within my sidebar navigation component, the sidebar.component.html file is structured as follows: <nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top" id="sideNav"> <a class="navbar-brand" href="#page-top"> <span cl ...

I am having trouble locating my TypeScript package that was downloaded from the NPM registry. It seems to be showing as "module not found"

Having some challenges with packaging my TypeScript project that is available on the npm registry. As a newcomer to module packaging for others, it's possible I've made an error somewhere. The following sections in the package.json appear to be ...

typescript error: referencing a variable before assigning a value to it in function [2454]

I am currently in the process of creating a store using nextJS I have two variables that are being assigned values from my database through a function let size: Size let ribbonTable: Ribbon async function findSizeCategory(): Promise<v ...

Module 'fs' or its type declarations could not be located

I am facing an issue with TypeScript not recognizing the 'fs' module. The error I receive is as follows: Error: src/app/components/drops/drops-map/drops-map.component.ts:9:29 - error TS2307: Cannot find module 'fs' or its correspond ...

What is the best way to utilize TypeScript module augmentation with material-ui components?

I have gone through the answers provided in this source and also here in this link, but it appears that they are outdated. I attempted to enhance the type definition for the button component in various ways, including a separate typings file (.d.ts) as we ...

Creating a type-safe dictionary for custom theme styles in Base Web

In my Next.js project, I decided to use the Base Web UI component framework. To customize the colors, I extended the Theme object following the guidelines provided at . Interestingly, the documentation refers to the theme type as ThemeT, but in practice, i ...

Using constant variables as arguments in functions in TypeScript

While learning about TypeScript, I encountered some confusion regarding how it handles const variables. Let's consider a scenario where I define an interface for a number: interface MyNumber { value: number; } If I then create a constant MyNumbe ...

"Although TypeOrm successfully generates the database, there seems to be a connectivity issue

Attempting to set up a JWT authentication system using NestJs and SQLite. The code successfully generates the SQLite file, but then throws an error stating "Unable to connect to the database." Upon checking with the SQLite terminal, it became apparent that ...

A conditional type used with an array to return either an Error object or a generic type when the array is destructured

Within my Typescript project, I've implemented a Result type to be returned from functions, containing either an error or some data. This can take the form of [Error, null], or [null, Data]. Here's an example: type Result<Data> = [ Error | ...

Angular efficient approach to changing object properties

When working on creating or updating records, I encounter a problem with the length and cleanliness of my code. The dealTypeValues object varies based on the dealDispositionType (buyout or sale), resulting in lengthy and messy code. Does anyone have sugge ...

Tips on determining the data type for a personalized useFetch hook

I want to develop a useFetch hook to handle various types of data like objects and arrays. Is there a way to make it dynamic without specifying a specific type? Sample function useRequest(url: string, method: Method, data: any) { const [response, s ...

Submitting Data in Ionic 3 using Http Post and Storing in Sqlite with Angular 4

I am facing an issue while trying to post an array of contacts on a WebService. When I send the array, the data appears as NULL in the WebService response. I am confused about how to use Let params{} The error message shows "object undefined". Addition ...

Elements can only be added to the array at the 0th index

In the process of developing a function, I encountered an issue where all elements added to the array were only stored in Array[0] of the rowData. The data is retrieved from a database. private createRowData() { var rowData:any[] = []; thi ...

Oops! The API request was denied with error code 401 - Unauthorized in React

I have been working on incorporating an API into my front-end project using React/Typescript. The documentation for the API specifies that authorization requires a key named token with a corresponding value, which should be included in the header. To stor ...

Mapped types: Specify mandatory properties depending on whether an array of identical objects includes a specific string value

Can an object property be set to required or optional based on the presence of a specific string in an array within the same object? type Operator = "A" | "B" type SomeStruct = { operators: Operator[]; someProp: string; // this should be ...