Utilizing Jest and nest.js for testing with absolute paths

Looking at my jest configuration inside the package.json:

"jest": {
  "moduleFileExtensions": [
    "js",
    "json",
    "ts"
  ],
  "moduleDirectories":["node_modules", "src"], // attempted to address the issue this way
  "rootDir": "src",
  "testRegex": ".spec.ts$",
  "transform": {
    "^.+\\.(t|j)s$": "ts-jest"
  },
  "coverageDirectory": "../coverage",
  "testEnvironment": "node"
}

To my knowledge, Nest does not include a jest.config file, so modifying package.json is my best option.

Despite these changes, my code still does not work:

yarn run v1.22.5
$ jest
 FAIL  src/auth/auth.service.spec.ts
  ● Test suite failed to run

    Cannot find module 'src/auth/auth.service' from 'auth/auth.service.spec.ts'

      3 | import * as moment from 'moment';
      4 | import { RedisService } from '@custom/redis-client'; // this is in node_modules
    > 5 | import { AuthService } from 'src/auth/auth.service';
        | ^
      6 | import { ConfigService } from 'src/config/config.service';
      7 |
      8 | describe('AuthService', () => {

      at Resolver.resolveModule (../node_modules/jest-resolve/build/index.js:306:11)
      at Object.<anonymous> (auth/auth.service.spec.ts:5:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        3.486 s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I also attempted to add this to the jest config and tsconfig:

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

However, I encountered the following error with this setup:

yarn run v1.22.5
$ jest
 FAIL  src/auth/auth.service.spec.ts
  ● Test suite failed to run

    Configuration error:
    
    Could not locate module ./src/redis/redis.health.indicator mapped as:
    /home/aironside/Documents/sygnum/dev-environment/api-layer/src/$1.
    
    Please check your configuration for these entries:
    {
      "moduleNameMapper": {
        "/src\/(.*)/": "/home/aironside/Documents/sygnum/dev-environment/api-layer/src/$1"
      },
      "resolver": undefined
    }

      at createNoMappedModuleFoundError (../node_modules/jest-resolve/build/index.js:551:17)
      at Object.<anonymous> (../node_modules/@sygnum/redis-client/index.ts:1:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        3.183 s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

What could be missing here?

Here is my complete tsconfig:

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "rootDir": "./",
  }
}

Answer №1

Dealing with the same problem as well. Make sure to switch

"rootDir": "src"
to
"rootDir": "./"
and include
"modulePaths": ["<rootDir>"]
in your pakage.json

Your jest configuration should ultimately resemble this:

"jest": {
    "moduleFileExtensions": [
        "js",
        "json",
        "ts"
    ],
    "moduleDirectories": [
        "node_modules",
        "src"
    ],
    "rootDir": "./", // ***** CHANGE "rootDir": "src" to "rootDir": "./"
    "modulePaths": ["<rootDir>"], // ***** ADD "modulePaths": ['<rootDir>'], 
    "testRegex": ".spec.ts$",
    "transform": {
        "^.+\\.(t|j)s$": "ts-jest"
    },
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
}

This adjustment resolved the issue for me. Hoping it does the same for you too!!

Answer №2

In my Typescript projects, I utilize the ts-jest module in combination with Jest for both unit testing and E2E testing. To streamline the process, I have separate configuration files for each type of testing, while maintaining a common base module to avoid redundancy.

When importing files for testing, I do not need to specify the src/ directory path; instead, I use the regular paths underneath it. Moreover, my configuration includes plugins that support the usage of Typescript paths such as @LIBRARY and @MODULE in the source code.

The configuration file jest-base.config.js consists of:

const tsconfig = require('./tsconfig.json');
const moduleNameMapper = require('tsconfig-paths-jest')(tsconfig);

module.exports = {
    moduleNameMapper,
    preset: 'ts-jest',
    testEnvironment: 'node',

    rootDir: './',

    // Other configurations...
};

For unit tests, I employ the jest.config.js setup along with the command

jest --watchAll --config ./jest.config.js
. This file includes:

const JestBaseConfiguration = require('./jest-base.config');

module.exports = Object.assign(JestBaseConfiguration, {

    roots: [
        '<rootDir>/src',
    ],

    // Other configurations...
});

For End to End tests, I rely on jest-e2e.config.js paired with the script option

jest --watchAll --config ./jest-e2e.config.js
. The content of this configuration file is as follows:

const JestBaseConfiguration = require('./jest-base.config');

module.exports = Object.assign(JestBaseConfiguration, {
    moduleFileExtensions: ['js', 'json', 'ts'],

    // More configurations...
});

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

Angular's change detection mechanism triggers too frequently

I'm dealing with a situation in one of my controllers where I have the following code: @HostListener('window:resize') onResize() { this.currentWindowWidth = window.innerWidth; } This code determines different views to render based on the ...

Transforming instance of a Class into Json format for WebService

My goal is to retrieve an object of the Product class as a Json for a webservice. Despite successfully loading all the values into the object, I encounter an error when trying to return it as Json. Below is my method: <AllowAnonymous> <HttpGet&g ...

Only one ID is recognized by jQuery

I have a group of three checkboxes set up like this: <input id="image_tagging" class="1" type="checkbox" value="1" checked="checked" name="data[image_tagging]"> Now, I've created an AJAX function (which is functioning correctly), but it seems ...

Several middlewares using router.params()

Is it possible to include multiple middlewares as parameters in the function router.params() in Node-Express? I currently have the following setup: const checkAuth = (req, res, next) => {console.log("checking auth"); next()} const checkAuth = ...

Creating a dynamic sidebar based on roles in AngularJS

I'm looking to create a dynamic sidebar based on the user's role, which is stored in $rootScope.login. However, I'm unsure of how to integrate it into template.js. Below is my JavaScript code and I'm still relatively new to AngularJS. ...

Encountering an issue while trying to import the validator module in NextJS 13

I encountered a peculiar issue while trying to import a module. Nextjs presented the following error message: ./application/sign_in/sign_in_store.ts:2:0 Module not found: Can't resolve 'validator' 1 | import { createEvent, createStore } fr ...

Is there a way to access and read the console log of a specific website using Python code? I am looking to extract messages such as "ok" and "connected

Seeking guidance on how to interpret console log output for a specific website while automating with Python. Struggling to extract live console data through Selenium, as there's no built-in function for reading logs in real-time. Although I can acces ...

What is the best approach for managing optional object input parameters while also verifying the presence and accuracy of that specific property?

What is the best approach to handling a situation where a method has optional object member properties for the options object, but you still want to ensure the presence of that property with a default value in the resulting instance? Is creating a separate ...

Tips for navigating to a specific row within a designated page using the Angular Material table

Utilizing angular material, I have set up a table with pagination for displaying data. When a user clicks on a row, they are redirected to another page. To return to the table page, they must click on a button. The issue arises when the user needs to retu ...

Retrieve the player's name from the database using jQuery

How can I retrieve the text value from my scores table in the database? Here is an image of my score table: https://i.stack.imgur.com/CUiMw.png The Player_name is stored as Player_id, which is a foreign key from the players' table. While I c ...

Obtaining the mouse position in JavaScript in relation to the website, preferably without relying on jQuery

I came across this code snippet on Ajaxian, but I am having trouble using cursor.y (or cursor.x) as a variable. When I call the function with it that way, it doesn't seem to work. Could there be a syntax issue or something else causing the problem? f ...

Utilizing Javascript Conditional for Substitution

Currently, I have a JavaScript function that replaces all links with registration messages: <script> function replaceLinks() { var links = document.querySelectorAll('.restore a:link'); for (var i = 0; i < links.length; i++) { ...

Incorporating an Array into a JSON Object and transmitting it to a server

I have stored an Object in a .json file that contains only an Array. Now I want to prompt the user for a word and add it to this Array. Below are the relevant code snippets: function addWord() { let myWords = getWords(); let newWord = prompt("Ple ...

What is the best way to customize a MaterialUI outlined input using a global theme overrides file?

I've been working on customizing my theme file with overrides, and I've encountered a strange bug while trying to style the outlined input. It seems like there are two borders appearing when these styles are implemented. https://i.stack.imgur.co ...

Issue with slideout menu hyperlinks malfunctioning

Currently developing a site at , everything seemed ready for deployment until testing in 320x480 mode on mobile revealed that the links on the slideout menu were not working on any mobile device I tried, regardless of resolution or page. I've tried u ...

Is it common practice to include a variable in a function with the same name as the function itself?

Is it common practice to use a variable with the same name as the function within the function itself? const sum = function(arr) { let sum = 0; for(let i = 0; i < arr.length; i++) sum += arr[i]; return sum; }; Although this code runs s ...

What is the best way to extract the ID from an event in TypeScript?

HTML Code: <ion-checkbox color="dark" checked="false" id="1on" (ionChange)="onTap($event)" ></ion-checkbox> TypeScript Code: onTap(e) { console.log(e); console.log(e.checked); } I am trying to retrieve the id of the checkbox. H ...

Enhancing Website Visibility: Utilizing PHP and JQuery to Update Page Content for Viewers

Imagine having a social networking platform where users can post updates and see them appear in real-time on their timeline. The challenge arises when these updates are only visible to the user currently logged in on a specific device. How can we utilize j ...

Error: "the cart variable in the ctx object has not been defined"

A project I'm currently working on involves a pizza ordering app, and my current focus is on implementing the Cart feature. Each user has their own cart, which includes specific details outlined in cart.ts import { CartItem } from './cartitem&a ...

Is there a way to delete a field from a JSON object using JavaScript?

Searching for a way in Node.js to eliminate the date and operation fields from the database. Any suggestions on how to do this? Currently, all fields are being transferred to the FE. The collection pertains to MongoDB. collection.find({'recordType&ap ...