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.