Troubleshooting issue: Unable to locate library during testing with Nx, Jest, and Angular

In my nx monorepo, I have two apps (client, server) and 5 libraries (client-core, platform-core, etc). To include the libraries in the Angular client application, I set the paths in the tsconfig.json file.

    "paths": {
      "@myorg/platform-core": [
        "../../libs/platform-core/src/index.ts"
      ],
      "@myorg/client-core": [
        "../../libs/client-core/src/index.ts"
      ],
    },

Everything works smoothly, as the IDE can resolve the libraries and I can run the application using ng serve. However, when I try to test the angular application with npx nx test client, it fails to locate the libraries.

 FAIL  apps/client/src/app/core/guards/patient.guard.spec.ts
  ● Test suite failed to run

    apps/client/src/app/core/guards/patient.guard.spec.ts:4:36 - error TS2307: Cannot find module '@myorg/client-core' or its corresponding type declarations.

    4 import { EnvironmentService } from '@myorg/client-core';
                                         ~~~~~~~~~~~~~~~~~~~

I attempted adding the same paths to tsconfig.spec.json (even though it should not be necessary since it extends 'tsconfig.json'), but that did not solve the issue.

What steps should I take to access these libraries from my spec files?

Answer №1

Which versions are you currently using? I encountered a similar issue while working on Angular 12 with jest 28. However, when I updated all my dependencies to Angular 14 and jest 28, the problems disappeared. One helpful tip is that utilizing yarn workspaces can simplify resolutions without needing to use the paths property.

If your versions are already up to date, it appears that nx may also have difficulties with application-specific paths. There was an (closed) issue related to this:

For those experiencing a "Module not found" error. If tsconfig.app.json's baseUrl points to the application source instead of the workspace root, linking between modules might not work properly. I personally saw improvement when I either removed the baseUrl from tsconfig.app.json or directed it towards the workspace root. Make sure that your tsconfig.json (or in the latest nx version, tsconfig.base.json) located in the workspace root still includes the correct baseUrl.

Check out https://github.com/nrwl/nx/issues/738

Answer №2

An easy fix might be to include the library path in your jest.json, similar to how you did it in the tsconfig.json. Here's an example:

  "moduleNameMapper": {
    "@myorg/client-core": "<rootDir>/../../libs/client-core/src/index.ts"
  }
  • Remember to use <rootDir>, followed by the path to the index file or source directory.

Answer №3

After troubleshooting, I found a solution that worked well for me.
Instead of the usual command to run unit tests like npx nx test client, I had success by specifying the project name in the following format:

npx nx test nx-project-name --test-file=src/app/app.component.spec.ts

Alternatively, if you need to test libraries,

npx nx test nx-project-name --test-file=libs/lib-name

Please note: This method was tested with Nx Standalone apps, but it should also work for monorepos since the project name and path are explicitly provided.

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 2 fails to redirect to a 404 page if both the route parameter and address are not valid

Currently, while working on my application with Angular 4.1.1, I have a habit of declaring routing in every module I create. For instance, in the file new-cars.routing.module.ts: import { NgModule } from '@angular/core'; import { RouterModule, ...

Leverage the power of InfiniteSWR in your project by integrating it seamlessly with

If you're looking for a comprehensive example of how to integrate useSWR hooks with axios and typescript, check out the official repository here. import useSWR, { SWRConfiguration, SWRResponse } from 'swr' import axios, { AxiosRequestConfig, ...

Development of an Angular 4 application utilizing a bespoke HTML theme

I'm in the process of creating an Angular 4 project using Angular CLI and I need to incorporate a custom HTML theme. The theme includes CSS files, JS files, and font files. Where should I place all of these files? Should they go in the asset folder? O ...

Unable to organize the data associated with a specific column in the header within an Angular material Table

viewing clinical history data the output I'm receiving is not in ascending or descending order Trying to organize the data in the table, utilizing the MatTableModule module alongside other required modules. However, after conducting research, I have ...

Using Angular 2 to showcase icons in the navbar post authentication

The structure of my components is as follows: The app component contains a navigation bar and router outlet. The navigation bar includes a logo, generic links, and specific links that are only shown after user login and authentication. The router outlet de ...

An error was encountered at line 52 in the book-list component: TypeError - The 'books' properties are undefined. This project was built using Angular

After attempting several methods, I am struggling to display the books in the desired format. My objective is to showcase products within a specific category, such as: http://localhost:4200/books/category/1. Initially, it worked without specifying a catego ...

An unassigned variable automatically sets the disabled attribute to true on an input field

Is this behavior a problem or normal? Consider the following form structure: <form #form="ngForm" > <div> <label>field1</label> <input type="text" name="field1" [(ngModel)]="mainVar" [disabled]="someVar" /> ...

Adding fresh 'observers' to a list of 'observers' while the application is running and monitoring updates by utilizing combineLatest in Angular

In my current scenario, I am facing a challenge of managing a list of observables that are constantly being updated by adding new observables to it during the application's runtime. Within this list, I am using combineLatest to perform API calls wit ...

TS: How can we determine the type of the returned object based on the argument property?

Assume we have the following data types type ALL = 'AA' | 'BB' | 'CC'; type AA = { a: number; }; type BB = { b: string; }; type CC = { c: boolean; }; type MyArg = { type: ALL }; I attempted to create a mapping between type n ...

Does angular-sortablejs work with angular 5?

I attempted to use angular-sortables in combination with the ng-drag-drop library to sort the list items that are being dragged, but it appears that nothing is happening when I try to use it. Does anyone know if angular-sortables is compatible with Angular ...

Using a pipe in multiple modules can lead to either NG6007 (having the same pipe declaration in more than one NgModule) or NG6002 (failing to resolve the pipe to an NgModule

My Pipe is located in apps\administrator\src\app\modules\messenger\pipes\custom-message.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; /** * Pipe for Custom Message for boolean */ @Pipe({ name ...

Issue encountered while utilizing npm on Visual Studio 2015

I'm attempting to run my Angular2 project with Visual Studio 2015. It works perfectly when I start it using npm in the windows console with the command 'npm start'. However, when trying to do the same thing using npm Task Runner for VS, I e ...

Encountered a resource loading error while launching a Spring-Boot Application with an Angular 7 Frontend due to missing resources

tag, I am eager to construct a Spring-Boot-Application with an Angular frontend. Initially, I utilized the Spring-Boot-Initializer to establish a project and incorporated a RestController for /greet/world. Following that, in my src/main-folder, I initiate ...

Tips for creating a Bitbucket pipeline to deploy an Angular Universal application

I'm currently working on deploying my Angular universal app on a server using Bitbucket pipelines. The scripts I've written in bitbucket-pipelines.yml are as follows: pipelines: default: - step: name: Build app caches: ...

Retrieve all values of a specific enum type in TypeScript

When working with Typescript, I am looking to retrieve all values of an enum type and store them in an array. In C#, a similar method would look like this: public static TEnum[] GetValues<TEnum>() where TEnum : Enum { return Enum.GetValues(typeof ...

Tips for building a diverse array of data types and effectively utilizing them based on their specific type in Typescript

Trying to store both custom types, Graphic and Asset, in the same array is proving to be a challenge. The goal is to access them and retain their individual type information. const trail: Array<Graphic | Asset> = []; for (let index = 0; index < t ...

Prisma atomic operations encounter errors when attempting to update undefined values

According to the Prisma Typescript definition for atomic operations, we have: export type IntFieldUpdateOperationsInput = { set?: number increment?: number decrement?: number multiply?: number divide?: number } Let's take a look at the Pris ...

Angular: Changing the class of a parent element dynamically while iterating through a list with ngFor

I have a unique challenge where I am trying to style a checkbox as a button by placing it inside its label. <label> <input type="checkbox" name="..."> </label> My goal is to toggle the parent label's class based on whether the che ...

Error in Angular 2: Uncaught Promise TypeError - Unable to access property 'title' of undefined

Whenever I attempt to include a text input field with dual binding in my App, the following error pops up: ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'title' of undefined TypeError: Cannot read property 'title&ap ...

Encountering a Windows 11 issue: npm ERR! errno -4058 with ENOENT bash code

Encountered a troublesome NPM issue suddenly, after taking a brief break from working on my project. Facing the following error with core-js. npm ERR! code ENOENT npm ERR! syscall spawn bash npm ERR! path C:\Users\User1\Documents\projec ...