What could be causing jest to throw an ERR_UNKNOWN_FILE_EXTENSION error when attempting to utilize a ts file as a custom testEnvironment?

I'm currently in the process of migrating my TypeScript project to a (pnpm) monorepo setup and encountering difficulties with running tests successfully. The issue seems to be related to jest, as I have a jest.config.js file that specifies a custom testEnvironment written in TypeScript. After moving the specific project into the packages directory for the monorepo restructuring, jest throws an Error and refuses to run any tests:

    TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for C:\workspaces\repos\the-monorepo\packages\testproject\source\testtools\jsdom-environment-global.spec.ts

I attempted to resolve the problem using @swc/jest and ts-jest, consulted resources like How to use TypeScript in a Custom Test Environment file in Jest? only to wonder why it worked previously. Despite clearing jest cache and reinstalling all node_modules, the issue persisted. Suggestions about adding

"type": "module"
in package.json were not applicable to my package since it's not ESM.

Below is a snippet of how the jest.config.js appears:

/** @type {import('@jest/types').Config.InitialOptions} */
const config = {
    silent: true,
    testEnvironment: "<rootDir>/source/testtools/jsdom-environment-global.spec.ts",
    roots: [
        "<rootDir>/source"
    ],
    maxWorkers: "50%",
    transform: {
        "^.+\\.(t|j)s$": ["@swc/jest", {
            sourceMaps: "inline",
            module: {
                strict: false,
                strictMode: false
            },

            jsc: {
                target: "es2021",
                parser: {
                    syntax: "typescript",
                    dynamicImport: true
                }
            }
        }]
    },
    transformIgnorePatterns: [
        "node_modules"
    ],
    testMatch: [
        "**/*/*.spec.ts",
        "**/*/*.test.ts",
        "!**/playwright-tests/**",
        "!**/playwright-tests-smoke/**"
    ],
    moduleFileExtensions: ["ts", "js", "node", "json"],
    reporters: [
        "default"
    ],
    globals: {
        self: {},
        navigator: {},
        jasmine: {},
        __UNIT__: true
    },
    coverageDirectory: "test-results",
    collectCoverage: false,
    collectCoverageFrom: [
        "./source/**/*.ts"
    ],
    coveragePathIgnorePatterns: [
        "/\\.spec\\.ts$/i",
        "/.*node_modules.*/",
        "/.*testtools.*/"
    ],
    coverageReporters: [
        "lcov", "cobertura"
    ],
    coverageProvider: "v8",
    resetMocks: true,
    restoreMocks: true,
    resetModules: true,
    setupFilesAfterEnv: [
        "jest-extended/all",
        "<rootDir>/source/testtools/setup.spec.ts"
    ],
    testPathIgnorePatterns: [
        "<rootDir>/source/testtools/",
        "<rootDir>/source/smoke-tests/",
        "<rootDir>/source/performance-tests/",
        "<rooDir>/source/playwright-tests/",
        "<rooDir>/source/playwright-tests-smoke/"
    ],
    moduleNameMapper: {
        "^@test-helpers": "<rootDir>/source/testtools/index.spec.ts",
        "^@test-tools/(.*)": "<rootDir>/source/testtools/$1",
        '^(\\.{1,2}/.*)\\.js$': '$1'
    }
};
module.exports = config;

The main question is why jest is struggling to interpret the testEnvironment when it's a TypeScript file?

Answer №1

Upon further investigation, I have identified the issue: there appears to be some confusion regarding the transformer not being applied to ESM files. Specifically, in my situation, the jsdom-environment-global.spec.ts file imported an ESM module from a different package within my monorepo. This import caused an exception because jest attempted to import it using require(), which was caught and then re-imported using dynamic imports. This dynamic import then resulted in the exception that ts is an unknown exception. It is unclear why these files were not transformed, but according to How to use TypeScript in a Custom Test Environment file in Jest?, this behavior seems to be typical.

To summarize: avoid importing from ESM files within your jest testEnvironment module.

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

Dealing with errors and fetching them within a react application using the useState hook

As a newcomer to React, I am currently working with a backend API in my project. One issue I encountered involves the "Login Page" functionality. When a user enters an incorrect username or password and submits the form, the API responds with a message sta ...

JavaScript implementation causing Safari to display a blank page

After diving into JavaScript recently, I encountered some issues right away. I've been attempting to run a simple "Hello World" program but no success so far. Each time I open the html file in Safari, it displays only a blank page. Despite having enab ...

A step-by-step guide on utilizing the reduce function to calculate the overall count of a user's GitHub repositories

I need help finding the total number of repositories for a specific user. Take a look at my code below: Javascript const url = "https://api.github.com/users/oyerohabib/repos?per_page=50"; const fetchRepos = async () => { response = await f ...

How can you choose the active tab when using Material UI Tabs in conjunction with React Router?

Combining React, Material-UI, and React-Router, I've successfully integrated React-Router with Material-UI tabs. Everything functions properly within the app itself. However, there's a minor issue when a user directly enters a specific route in t ...

Develop a new flow by generating string literals as types from existing types

I'm running into a situation where my code snippet works perfectly in TS, but encounters errors in flow. Is there a workaround to make it function correctly in flow as well? type field = 'me' | 'you' type fieldWithKeyword = `${fiel ...

Checkbox click event not triggering properly

I am facing challenges in triggering an onclick event for the "Elevation" checkboxes located at the URL provided above. <input type="checkbox" value="A" id="elevation_A" onclick="changeElevation(this.value);" /> For some reason, the "changeElevati ...

Is there a way to identify the presence of a mouse on a website?

In the process of developing a website, I encountered a dilemma with navigation buttons. They needed to be large for aesthetic reasons and ease of use but had to be small when not in use. To address this, I decided to shrink the buttons into thumbnails on ...

Tips for reading user input in a terminal using node.js

Before deploying my code to the server, I'm looking to conduct some local node testing. How can I take terminal input and use it as an input for my JavaScript script? Is there a specific method like readline that I should be using? ...

Initial binding of Angular2 ControlGroup valueChanges event

My form contains <input type="text"> elements and I've noticed that ControlGroup.valueChanges is triggered during initial data binding when using [ngFormModel] and ngControl. As a result, it gives the impression to the user that the form has al ...

My function handler is not being triggered when using React's onClientClick

I'm facing an issue with a button component I have, let's refer to it as < MyButton >. <MyButton onClick={this.props.calculate} onClientClick={this.changeColor} > Calculate </MyButton> Whenever I click the button, my cal ...

What could be causing the sluggish performance of this particular MongoDB query?

I'm currently grappling with how to manage a particular situation that will eventually involve date ranges. db.article_raw.count({ "date": {$gt:ISODate("2015-07-08T00:00:00.000Z")}, "searchTerms.term":"iPhone" }) Despite knowing that my indexe ...

Assistance required in utilizing Objective C to run Javascript for automatically populating web forms

I've been grappling with this issue for a while now and I can't seem to make any progress. As someone who isn't well-versed in JavaScript, I've scoured various forums and websites for a solution but to no avail. My current challenge in ...

typescriptIs there a more efficient approach to typing optional values without a default value in

In my React application with TypeScript, I am using the following code to provide typed props: type ScheduleBoxContentProps = { desc: ReactNode, lottie: LottieProps, } & Partial<{className: string}>; I want the className prop to be optional ...

Switch the timezone to GB for all individuals accessing the page

My current code checks if a user falls within a specific time range (9.00am - 17.30pm) Monday to Friday. function checkTime() { var d = new Date(); // current time var hours = d.getHours(); var mins = d.getMinutes(); var day = d.getDay(); ...

Are there any uncomplicated JavaScript tools for creating spreadsheets?

I am in the process of developing a basic web-based expense calculator using asp.net web forms. Each cell will contain a text box, and the objective is to save each value (excluding the totals) to a database. I plan to have an expense table and an expense_ ...

directive ng-click not responding

drawer-card.html (template) <div class="drawer-card-wrapper"> <div class="drawer-card-icon" ngClick="dcCtrl.toggle()"> <i class="icon--{{ icon }}"/> </div> <div class="{{'drawer-card ' + (classesToAdd || '&apo ...

How can I extract and display data from a MySQL database in cytoscape.js?

I have a database table called 'entrezgene' that contains geneID and name fields. These fields will be used to create nodes in cytoscape.js. Additionally, I have another table named 'interaction' with geneID and geneID2 fields, which wi ...

Differences between Array `forEach` and `map()`

I am having trouble displaying the options list even though I am passing an array. Any assistance would be greatly appreciated. Thank you. const options_A = [ { label: "AA", value: "AA" }, { label: "BB", valu ...

What should I do when using _.extend() in express - override or add in fields?

When an object is extended by another object with values set for some of the extended fields, will it be rewritten or will the new values be added? For example: const PATCH_REQUEST_SCHEMA = { 'type': 'object', 'title' ...

Is it possible to attach "traits" to a current array of objects using TypeScript?

I have a variety of object types that I need to manipulate within an array consisting of those object types. type AB = { a:number, b:number} type CD = { c:number, d:string} type DE = { d:number, e:boolean} let state: AB[] = [] function onStateChange(newSt ...