When running the test, a "is not defined" ReferenceError occurs in the declared namespace (.d.ts) in ts-jest

When running typescript with ts-jest, the application functions properly in the browser but encounters a ReferenceError: R is not defined error during testing.

The directory structure:

|--app
|   |--job.ts
|--api
|   |--R.d.ts
|--tests
|   |--job.test.ts

and the corresponding files:

//job.ts
export default class Job{
    private static cmd:R.P.CMD

    constructor(){
        Job.cmd=R.P.getCMD()
    }
    //....
}

and the test file:

// job.test.ts
import { describe, expect, test, jest, beforeEach } from '@jest/globals';
import Job from '../app/job'

describe('Test Job',()=>{
    test('job init',()=>{
        let job = new Job()
        //....test code
    })
})

R.d.ts definition:

declare namespace R{
    //....
}
declare namespace R.P{
    function getCMD(): MyInterface
//...
}

Configuration details,

//jest.config.js
/** @type {import('ts-jest').JestConfigWithTsJest} */
export default {
    preset: "ts-jest",
    testEnvironment: "jsdom",    
    moduleDirectories: ["node_modules", "<rootDir>"],
    moduleNameMapper: {
        "^(\\.{1,2}/.*)\\.js$": "$1",
    },
    transform: {
        "^.+\\.{ts|tsx}?$": [
            "ts-jest",
            {
                allowJs: true,
                useESM: true,
            },
        ],
    },
};

In tsconfig.json:

{
"compilerOptions": {
    "target": "ES2019",                            
    "moduleResolution": "Node",                
    "baseUrl": "./",           
    "types": [
      "./api/R"
    ],                                

    "allowJs": true,            
    "sourceMap": true,            
    "outDir": "js",              
    "allowSyntheticDefaultImports": true,            
    "esModuleInterop": true,                             
    "forceConsistentCasingInFileNames": true,            
    "strict": true,                                      
    "skipLibCheck": true                                 
  },
  "files": [
    "./api/R.d.ts"
  ],
  "include": ["./app/**/*.ts"],
  "exclude": ["node_modules","**/*.test.ts","./tests/"]
}

I attempted to import the R.d.ts file in job.test.ts: import '../api/R.d.ts' but encountered the same error. According to the documentation on Babel7 and namespaces, it appears Babel7 does not support namespaces. However, I am not using Babel. The packages being used are:

    "@types/jest": "^29.5.11",
    "jest": "^29.7.0",
    "jest-environment-jsdom": "^29.7.0",
    "ts-jest": "^29.1.1",
    "typescript": "^5.2.2"

Update: the R.d.ts pertains to a JavaScript library:

|--app
|   |--job.ts
|--api
|   |--R.d.ts
|   |--r-api.js
|--tests
|   |--job.test.ts

Jest can locate the R.d.ts file (as seen by usingjest.mock() and import '../api/R.d.ts'), but it seems unable to interpret the file correctly.

Answer №1

Doing things this way may not be conventional, but it allows my tests to run smoothly without encountering the error message R is not defined. Here's what worked for me:

  1. Create a dummy file in the api directory: /api/__mocks__/R.d.ts
declare namespace R{
    //...
}
declare namespace R.P{
    function getCMD(): any
//...
}
  1. Reference the mocked .d.ts file in your test file:
    /// <reference types='../api/__mocks__/R.d.ts'/>
  2. Within the test file,
global['R'] = {
 P: {
    getCMD: jest.fn().mockImplementation(() => { }),
   }
}
  1. Update jest.config.json by setting isolatedModules:true

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

Even though there is data stored in the array, the React Native array.length appears to be returning a value

I am struggling with what appears to be a simple issue, and it's frustrating that I've had to seek help for this. The problem lies in iterating through an array messages: Message[] = [...]. No matter what method of iteration I try, it doesn&apos ...

Choosing From Optional Symbols

Is it feasible to create a custom utility type in TypeScript that resembles the Pick-style, allowing for specified keys that may or may not exist on the selected object type? For example: interface Alpha { a: boolean; b: boolean; } type Selecte ...

The `process` variable is not recognized in a Vue/TypeScript component

I've encountered an issue trying to use .env variables in my Vue app. When I ran npm install process, the only syntax that didn't result in an error when importing was: import * as process from 'process'; Prior to this, I received the ...

Refresh the array using Composition API

Currently, I am working on a project that utilizes Vue along with Pinia store. export default { setup() { let rows: Row[] = store.history.rows; } } Everything is functioning properly at the moment, but there is a specific scenario where I need to ...

Where's the tsconfig.json for Firebase Emulators?

I've encountered an issue with my Firebase project that's written in JavaScript (not TypeScript). When attempting to run the functions emulator, I'm getting the following error: $ firebase emulators:start --only functions ⚠ functions: Ca ...

The data type '{ [key: string]: number; }' cannot be assigned to type 'T'

I’m working with a complex TypeScript type and trying to manage it within a function. Here’s what I have: type T = { a: number } | { b: number } function func(k: 'a' | 'b', v: number) { // error message below const t: T = { ...

Should I return X in async functions, or should I return "Promise.Resolve(X)"?

I've always found this to be a tricky concept to fully grasp. Let's delve into async functions in Typescript. Which implementation is accurate? async function asyncFunctionOne(string1: string, string2: string, string3: string) { var returnOb ...

Can you explain the significance of using an exclamation mark after defining a variable in TypeScript?

As I delve into TypeScript in an effort to enhance my programming skills, I have encountered the use of exclamation marks when defining variables. An example of this can be seen in the following code snippet: protected _db!: CheckpointDB ...

Record the variable as star symbols in the VSTS Extension

I am working on a VSTS extension using Typescript and utilizing the vsts-task-lib Currently, I am encountering an issue with the execSync function, which displays the command being executed. However, I need to hide a token obtained from a service by displ ...

There seems to be a console error in Angular 5 when using IE 11

I've developed an Angular 4 application using MVC and Visual Studio 2015. Everything runs smoothly when I access the application on Chrome, but I encounter the following exception on IE 11: XHR error: (404 Not Found) loading http://localhost/src/ma ...

Creating dynamic keys to insert objects

In my coding project, I am dealing with an empty array, a value, and an object. Since there are multiple objects involved, I want to organize them into categories. Here is an example of what I envision: ARRAY KEY OBJECT OBJECT KEY OBJECT ...

Issue in VueJs where mutations do not properly save new objects to the state

I am facing an issue with updating my vuex store after modifying my user credentials in a component. Below is the code snippet for reference: mutations: { updateUserState: function(state, user) { state.user = user; }, } actions: { updat ...

What is the best way to define a category in order to utilize a saved string as a variable for referencing it?

An object named CONFIG holds the following information: export const CONFIG = { buttonDestinations: { detailedStats: `detailedStats`, mealPlans: `mealPlans`, products: `products` }, buttonTexts: { detailedStats: ...

Why is the getElement().getProperty("value") function not functioning properly?

I am facing an issue with reading a property in my web component. I am puzzled as to why it is not working correctly. I created a simple example, and after clicking the button, I expect to retrieve the value of the property, but it returns null. I am unsur ...

Tips for expanding third-party classes in a versatile manner using Typescript

tl;dr: Seeking a better way to extend 3rd-party lib's class in JavaScript. Imagine having a library that defines a basic entity called Animal: class Animal { type: string; } Now, you want to create specific instances like a dog and a cat: const ...

Error in Angular 13: Struggling to remove the likelihood of an object being null

I am working on a piece of code that includes the following: var item = document.getElementById("div0"); item.parentNode.removeChild(item); // The error seems to be here Every time I run this code, I encounter the error message: object is p ...

The TypeScript class for Date has a property that outputs a string

In my TypeScript code, I have defined a model class as follows: export class Season { ID: number; Start: Date; } Below is an example of how this model class is utilized within a component: export class SeasonsComponent { seasons: Season[]; sele ...

Testing Ag Grid's column headers using Jest and Angular CLI has proven challenging, as some columns from columnDefs remain elusive

Currently, I am using Jest and Angular Cli testing to validate column headers. In my attempt to replicate the process outlined on https://www.ag-grid.com/javascript-grid-testing-angular/#testing-grid-contents, I have encountered an issue where only 2 out ...

Creating Typescript packages that allow users to import the dist folder by using the package name

I am currently working on a TypeScript package that includes declarations to be imported and utilized by users. However, I have encountered an issue where upon publishing the package, it cannot be imported using the standard @scope/package-name format. I ...

Methods for organizing consecutive elements within an array in Javascript/Typescript

Let's explore this collection of objects: [ { key1: "AAA", key2: "BBB" }, { key1: "BBB", key2: "CCC" }, { key1: "CCC", key2: "DD ...