Tips for utilizing jest.mock following the removal of @types/jest (^jest@24)

After upgrading from version 7 to version 8 of @angular-builders/jest, I followed the instructions provided in the migration guide which advised removing @types/jest since it now comes bundled with Jest v24. Additionally, changes were made to my tsconfig as recommended in the guide.

Everything seemed fine until my tests started failing with the following errors:

Error TS2304: Cannot find name 'jest'.

jest.mock('src/app/omitted');

Error TS2304: Cannot find name 'jest'.

jest.clearAllMocks();

VS Code also did not recognize the jest global variable anymore, which is understandable considering the removal of typeRoots from the tsconfig file based on the migration guide's suggestions.

In tsconfig.json (root directory, used by IDE):

Remove typeRoots array

As Jest typings are now part of the Jest package and no longer found under node_modules/@types, restricting the type roots to a specific folder is unnecessary.

But why am I facing these issues? The guide instructed me to remove @types/jest, so how can I resolve the conflicts with jest.mock and jest.clearAllMocks?

I attempted the following solutions without success:

import { mock } from 'jest'; // unable to find mock
import * as jest from 'jest'; // unable to find jest.mock

Any advice would be greatly appreciated.

Below are my configurations (same as the simple-app example):

relevant dev packages

{
    "@angular-builders/jest": "^8.0.3",
    "jest": "^24.8.0",
    "jest-preset-angular": "^7.1.1",
    "ts-jest": "^24.0.2",
}

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "esnext",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "lib": ["es2018", "dom"],
    "strict": true                
  }
}

tsconfig.spec.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "allowJs": true
  },
  "files": ["src/polyfills.ts"],
  "include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
}

angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "my-project": {
      //...
      "architect": {
        //...
        "test": {
          "builder": "@angular-builders/jest:run",
          "options": {}
        }
      }
    }
  }
}

Answer №1

@types/jest is still necessary according to this discussion. The recent update to the migration guide reflects this requirement.

Here are the updated configuration settings:

package.json

"@angular-builders/jest": "^8.0.3",
"@types/jest": "^24.0.15",
"jest": "^24.8.0",
"jest-preset-angular": "^7.1.1",
"ts-jest": "^24.0.2",

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "esnext",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "lib": ["es2018", "dom"],
    "types": ["jest"],
    "strict": true                     // note strict mode, this isn't default
  }
}

tsconfig.spec.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec"
  },
  "files": ["src/polyfills.ts"],
  "include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
}

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

Callback for dispatching a union type

I am currently in the process of developing a versatile function that will be used for creating callback actions. However, I am facing some uncertainty on how to handle union types in this particular scenario. The function is designed to take a type as inp ...

Is there a way to configure routerLinkActive specifically for these routes?

My website has a navigation bar with the following items: Users, Categories, Products, etc. The routes are set as Main/Users, Main/Categories. I have successfully highlighted the items using routerLinkActive, however I also want to highlight the Users item ...

Error encountered while attempting to obtain OAuth2 API authorization token in ExpressJS Node.js Angular: "getaddrinfo ENOTFOUND"

Recently, I developed an angular application that sends an HTTP post request to a Node/Express.js endpoint upon clicking a button in order to obtain an authorisation token. I successfully configured the necessary credentials for basic OAuth2 authorisation ...

Unable to determine the data type of the JSON object during the

I'm having trouble reading an Object type of json... Here is the json I'm working with: body: { "111": { "name": "name1", "status": 10000 }, "222": { "name": "name2", "status": 20000 }, "333": ...

The issue of "Angular library throwing an error outside the specified 'rootDir' directory" arises while attempting to share dependencies

I've been hearing a lot about being able to utilize modules, components, and interfaces in an Angular library. However, I'm constantly encountering an error that says outside of the configured 'rootDir'. projects - app - lib - c ...

Guide on submitting a form through the Angular 2 HTTP post method with JavaScript

Currently working on grasping the concepts of Angular2, but facing challenges when attempting to utilize http.post() for submitting a form to my Web API. ...

Pipe for Angular that allows for searching full sentences regardless of the order of the words

I am looking to create a search bar that can search for the 'title' from the table below, regardless of the word order in the sentence. I attempted to use a filter pipe to check if the search string exists in the title. I also experimented with ...

Issue with caching when using lazy loading with Angular 2 components

When naming Angular 2 lazy loaded components, they are designated as 0.js, 1.js, etc. However, the entry point is given a version prefix while all lazy loaded components keep their original names. This leads to discrepancies in the code versions present ...

Choosing an option in Angular 2 based on a specific condition

My question is about a select element: <select id="position"> <option *ngFor='#contactType of contactTypes' [attr.value]='contactType.contactTypeId'> {{contactType.description}} </option> </select ...

The power of Vue reactivity in action with Typescript classes

Currently, I am working on a Vue application that is using Vue 2.6.10 along with Typescript 3.6.3. In my project, I have defined a Typescript class which contains some standard functions for the application. There is also a plugin in place that assigns an ...

Is it possible to designate a Typescript generic type as a tuple with equal length to that of another tuple?

Imagine having a function that takes in a dataset which is an array of (identically-typed) tuples: type UnknownTuple = any[] function modifyDataStructure<T extends UnknownTuple>(list: T[]) { ... } The goal is to define a second argument with the ...

Guide on executing get, modify, append, and erase tasks on a multi-parameter JSON array akin to an API within Angular

I have a JSON array called courseList with multiple parameters: public courseList:any=[ { id:1, cName: "Angular", bDesc: "This is the basic course for Angular.", amt: "$50", dur: & ...

Eliminating data type from union in Typescript

I have a specific type that I collect from various other types: type CustomType = { id: string; foo: (string | Type1)[]; bar: (string | Type2)[]; baz: string | Type3 | null; description: string | null; } I am interested in refining thi ...

What is the best way to bring in the angular/http module?

Currently, I am creating an application in Visual Studio with the help of gulp and node. Node organizes all dependencies into a folder named node_modules. During the build process, gulp transfers these dependencies to a directory called libs within wwwroo ...

Resolve the result of the HttpComponent within the Service component

Consider this example involving HttpClient: In Service configData: string[]; fetchData(): Observable<string[]> { return this.http.get<string[]>('./assets/config.json'); } getConfigValue(key: string): string { if ...

Tips for incorporating the Sanitize library into Angular 6:

What is the most effective library for sanitization in Angular 6 to enhance security measures? Since injecting dependencies can be tricky, what are some recommended methods for implementing this in an Angular 6 project? ...

The Material Table in Angular is having issues with sorting functionality

I tried implementing the basic example from the angular material website, which displays a table with accurate data but the sorting functionality is not working as expected. For reference, you can view the StackBlitz demo here: https://stackblitz.com/edit ...

simulating interaction with databases within API routes

I am currently working on developing a full stack application using NextJS along with a MySQL database. Within my API routes, I interact with this database by making calls to various functions such as createOne(), which is responsible for creating new inst ...

Error: A stream was expected, but you provided 'undefined'. Please provide either an Observable, Promise, Array, or Iterable instead

I'm encountering an error while trying to catch errors in my Ionic-based application with Angular. In the create() method, I am attempting to create a new User. If the username already exists, I receive a response from the backend, but my method thro ...

Unlock the Power of Angular with Custom Decorators: Accessing ElementRef Made Easy

I am currently working on implementing a decorator for Host CSS Variable Binding in Angular5. However, I am facing difficulties in properly implementing it with the given code. Is there a way to define ElementRef from within the decorator itself? export f ...