Search code examples
node.jstypescriptjestjses6-modulests-jest

Jest does not resolve ESM local imports


I have a Typescript project with two files, a.ts and b.ts. I import the latter in a.ts like this

import * from "./b.js"

This works fine. Typescript understands. However, when running Jest (using ts-jest), I get

Cannot find module './b.js' from 'a.ts'

How can I make Jest understand that the .js import is still a .ts file when running the test?


Solution

  • Already found it. I had to add the below to jest.config.ts

    moduleNameMapper: {
       '^(\\.{1,2}/.*)\\.js$': '$1',
    },
    

    It maps .js filenames to an extensionless version, which Jest (i.e. ts-node under the hood) can then find.

    Note: having preset: 'ts-jest' is also necessary, but I already had that before.