NestJS encountered an error while running the test suite: module 'src/article/article.entity' could not be located from 'comment/comment.entity.ts'

I am facing an issue with NestJS and Jest testing. As a newcomer to NestJS, I encountered the "Cannot find module" error when running tests.

Specifically, the error message I received while trying to test my service was:

src/article/article.service.spec.ts ● Test suite failed to run

Cannot find module 'src/article/article.entity' from 'comment/comment.entity.ts'

Require stack:
  comment/comment.entity.ts
  article/article.entity.ts
  article/article.service.spec.ts

   6 |   ManyToOne,
   7 | } from 'typeorm';
>  8 | import { Article } from 'src/article/article.entity';
     | ^
   9 | 
  10 | @Entity()
  11 | export class Comment {

  at Resolver.resolveModule (../node_modules/jest-resolve/build/index.js:307:11)
  at Object.<anonymous> (comment/comment.entity.ts:8:1)

This same error is occurring in various tests across different controllers and services.

Below is the code I am attempting to test:

article.service.ts

import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Article } from "./article.entity";
import { ArticleRepository } from "./article.repository";
import { ArticleDTO } from "./dto/article.dto";
import { DeleteResult } from "typeorm";
import { ArticleRO } from "./dto/article.response";
import { UserRepository } from "src/user/user.repository";

@Injectable()
export class ArticleService {
  constructor(
    private readonly articleRepository: ArticleRepository,
    private readonly userRepository: UserRepository
  ) {}

  async getAllPosts(): Promise<ArticleRO[]> {
    return await this.articleRepository.find();
  }
}

article.repository.ts

import { Repository, EntityRepository } from 'typeorm';
import { Article } from './article.entity';
@EntityRepository(Article)
export class ArticleRepository extends Repository<Article> {
}

article.service.specs.ts

import { Test, TestingModule } from "@nestjs/testing";
import { getRepositoryToken } from "@nestjs/typeorm";
import { Article } from "./article.entity";
import { ArticleRepository } from "./article.repository";
import { ArticleService } from "./article.service";
import { ArticleRO } from "./dto/article.response";

describe("PostService", () => {
  let service: ArticleService;
  let articleRepository: ArticleRepository;
  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        ArticleService,
        {
          provide: getRepositoryToken(Article),
          useClass: ArticleRepository,
        },
      ],
    }).compile();

    service = module.get<ArticleService>(ArticleService);
    articleRepository = module.get<ArticleRepository>(
      getRepositoryToken(Article)
    );
  });

  it("should be defined", () => {
    expect(service).toBeDefined();
  });
  describe("findAll", () => {
    it("should return an array of cats", async () => {
      const result: ArticleRO[] = [];
      jest.spyOn(service, "getAllPosts").mockResolvedValueOnce(result);

      expect(await service.getAllPosts()).toBe(result);
    });
  });
});


comment.entity.ts

import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  ManyToOne,
} from 'typeorm';
import { Article } from 'src/article/article.entity';

@Entity()
export class Comment {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  author: string;

  @Column()
  content: string;

  @CreateDateColumn()
  createdAt: Date;

  @ManyToOne(
    () => Article,
    article => article.comments,
  )
  article: Article;
}

Here are my Jest settings from package.json:

"jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".spec.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }

I attempted changing my rootDir to "./src" but that did not resolve the issue.

Upon generating the project using `nest new`, my Jest settings remained default. It's possible that I may have made an error with my custom repository mocking in the tests.

Answer №1

If you want Jest to resolve module paths in a specific way, you can set up the moduleNameMapper option. This is particularly handy if you're using tools like module-alias or if you prefer absolute paths. Simply add the following lines to your Jest configuration:

{
  // ...

  "jest": {
    // ...

    "moduleNameMapper": {
      "^src/(.*)$": "<rootDir>/$1"
    }
  }
}

With this setup, modules starting with src/ will be resolved to <rootDir>/, which typically points to the src folder (as defined earlier in the configuration). For more customization options, refer to the documentation provided above.

I disagree with the notion that using absolute paths is problematic, as it has been proven to work effectively in both NestJS and Angular projects.

Answer №2

Avoid utilizing paths such as "src/article/article.entity" within your application, as these will not be accessible post compilation. It is recommended to use relative paths like "../../article/article.entity" instead (please note that this path is just an approximation)...Best regards

Answer №3

Switching To Relative Imports

Plus the handy VSCode feature to make it easy.

I found myself needing to adjust my VSCode import settings to utilize relative paths for TypeScript. Initially, VSCode was importing using the "shortest" path format, such as src/auth/user.entity. Although my NestJS application compiled without issues, I encountered Jest testing errors similar to yours.

By modifying the setting TypeScript › Preferences: Import Module Specifier to relative, the modules now import in a format like ../auth/user.entity. (Be sure to update this setting specifically for TypeScript, as there is a parallel one for JavaScript. I made adjustments to both.).

This adjustment in module imports successfully resolved my problems with NestJS Jest testing, including those frustrating Cannot find module 'src/article/article.entity' from 'comment/comment.entity.ts' errors.

For more detailed information on changing the typescript preferences in VSCode, check out this link:

Answer №4

The problem I encountered was resolved by inserting the following code snippets into /test/jest-e2e.json

  "moduleNameMapper": {
    "^src/(.*)": "<rootDir>/../src/$1"
  }

Answer №5

To copy the relevant path of a file, right click on it and select "Copy Relevant Path", then paste the path and remove the file extension.

For example:

import { function_name } from '/paste the full relevant path here and remove the extension'

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 issue are we encountering with those `if` statements?

I am facing an issue with my Angular component code. Here is the code snippet: i=18; onScrollDown(evt:any) { setTimeout(()=>{ console.log(this.i) this.api.getApi().subscribe(({tool,beuty}) => { if (evt.index == ...

Transforming Boolean data types into text within an Angular 2 client-side application

Query I'm currently working on retrieving data from an API and displaying it in a table. One of the columns includes a status attribute that returns either true or false values. However, I would like to display "Active" or "Block" instead on the clie ...

Next.js routes taking precedence over storybook routes

I recently completed a storybook project. Now, I am looking to integrate it with another project built on next.js. The issue is that Storybook and next.js each have their own set of routes. I want to streamline the routing process by utilizing next.js and ...

Using a pipe filter to implement a search feature in an Ionic search bar

Hey everyone, I'm facing a little issue here. I created a pipe filter to sort through some data, but now I need to include two more filters and I'm not sure how to go about it within this pipe. Below is an example of the pipe I have created: ...

Transforming @Query() parameters into a DTO with intricate data types in NestJS

During my exploration of NestJS, I came across a challenge. Here is the DTO I am dealing with: export default class SearchNotesDto { query: string; createdAfter: Date; createdBefore: Date; } I want to retrieve this DTO when a GET request is made to ...

Apologies, but there was an unexpected error: Uncaught (in promise): TypeError: Unable to access the 'customerName' property of an undefined

Check out the structure of my JSON file: { "total": 3, "items": [ { "id": "01", "data": { "customerName": "Jhon", "description": "..some content..", "price": "25000" ...

Issue with HTTP Interceptor not being effective when making service calls

I've implemented an interceptor to automatically add headers to each HTTP request without manual intervention. However, I'm facing an issue where the service call inside my interceptor is not triggering for some reason. Below is the code snippet: ...

Troubleshooting common issues while setting up React Native with TypeScript

After carefully following the steps outlined in this guide on configuring a React Native project using TypeScript: https://facebook.github.io/react-native/blog/2018/05/07/using-typescript-with-react-native, I encountered a total of fifteen errors from the ...

The NodeJS application experiences a crash if incorrect parameters are provided to the API

Currently, I have built a CRUD API using TypeScript with Node.js, Express, and MongoDB. My goal is to ensure that the API functions correctly when the correct parameters are sent through a POST request. However, if incorrect parameters are passed, the Node ...

The specified '<<custom component name>>' argument does not match the 'Type<<custom component name>>' parameter

I'm currently facing an error that indicates a type parameters mismatch, but I can't pinpoint where in the process it's happening. Argument of type 'ModalUserInfoComponent' is not assignable to parameter of type 'Type<Mo ...

How can you load an HTML page in Puppeteer without any CSS, JS, fonts, or images?

My current task involves using Puppeteer to scrape data from multiple pages in a short amount of time. However, upon closer inspection, I realized that the process is not as efficient as I would like it to be. This is because I am only interested in spec ...

The file that is currently being downloaded has the .pptx extension, but it is being

Take a look at this code snippet: const generateDownload = ({ link, data, title, settings })=> { const newLink = document.createElement('a'); const blobUrl = link || URL.createObjectURL(new Blob([data], settings)); newLink.setAt ...

The code snippet for the React TypeScript Cheatsheet in the Portal sample appears to be malfunction

I have implemented a strict version of TypeScript and ESLint in my project. The code for this portal was originally sourced from the documentation available here: After making some modifications, the code now looks like this: import React, { useEffect, u ...

Error message: "ReferenceError occurred while trying to access the Data Service in

As I embark on the journey of creating my very first MEAN stack application - an online cookbook, I have encountered a challenge in Angular. It seems like there is an issue between the service responsible for fetching recipe data from the API (RecipeDataSe ...

Incorrect date generated by Moment.js from Unix timestamp

Is there a way to store unixtime as a Moment.moment state? Using moment(timestamp) seems to provide a different date. const [date, setDate] = useState<moment.Moment | null>(null); const timestamp = Math.floor(date.getTime() / 1000); setDate(m ...

What are the benefits of combining 'eslint' and 'typescript-eslint' for TypeScript linting as opposed to just using 'tsc'?

Objective: Developing a rigorous TypeScript linter script eslint scans for problematic JavaScript code patterns. The documentation recommends initiating eslint with npm init @eslint/config@latest This process also installs typescript-eslint But what is ...

Ensuring Type Safety for Collections in TypeScript

My code snippet looks like this: portfolioList: MatTableDataSource<Portfolio>; ngOnInit(): void { this.backend.getStatement().subscribe( list => { if(list as Portfolio[]) this.portfolioList = new MatTableDataSource(l ...

Analyzing data from an Excel spreadsheet and performing specialized mathematical operations

I am in need of a python script that can read an excel file with 27 columns, extract the final five values of each column, and perform various mathematical operations on those numbers. My current progress is as follows: from math import tan #Write Heade ...

Discover the wonders of utilizing @blur events on your custom Vue components!

Trying to create a customized component that mimics an input field with validation, I'm encountering issues with getting @Change, @blur, and other events to function properly as they would on a standard input field. This is the structure of my custom ...

Developing a front-end Angular application with a back-end C# API to handle posting of form data, including files

Seeking assistance with understanding how to upload a file (FormData) and an object from Angular to C# API. It seems that the HttpClient post method can only accept one body parameter, so I am unable to post both the FormData object and the SomeObject obje ...