Search code examples
node.jsjestjsts-jest

What is the (smallest) setup to allow import to be used by Jest?


I'm having trouble running a module test in Node. I don't have an existing project, and I can't find one that has tests using import statements.

In Jest's Getting Started guide, there is a line that I want to use: import {sum} from './sum'; When I use that instead of const sum = require('./sum'); it errors with:

    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { sum } from './sum';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

Given I've successfully followed the instructions in the first section before "Additional Configuration", what are the minimum changes required to get the import statement working?

(Node 22.8.0, jest 29.7.0, ts-jest 29.2.5) - it shouldn't be experimental any more?


Solution

  • Well, it seems like transpiling is still required to get this to work.

    The key thing is to update the package.json to include

      "jest":{
         "preset": "ts-jest"
      }
    

    that preset line could be replaced with:

      transform: {
        "^.+.tsx?$": ["ts-jest",{}]
      }
    

    (at least for the purposes of fixing the import statement issue)