ts-jest icon indicating copy to clipboard operation
ts-jest copied to clipboard

[Bug]: Using dynamic import of ESM library yields "Cannot find module"

Open joaorodrigues-consensys opened this issue 2 years ago • 1 comments

Version

28.0.7

Steps to reproduce

  1. Clone my repo at: https://github.com/joaorodrigues-consensys/test-lodestart-libs
  2. nvm use
  3. npm install
  4. npm run test

Expected behavior

Expected test to pass

Actual behavior

Tests failed: error TS2307: Cannot find module '@lodestar/params' or its corresponding type declarations.

This is a full ESM library that has to use dynamic import (await import()). Application works fine (e.g.: npm run build or npm run start).

Debug log

ts-jest.log

Additional context

We've got a statement in the code of a dynamic import of an ESM package:

const p = await import('@lodestar/params')

This code runs well at runtime (i.e.: application running) and the module is correctly imported. However, it fails when running tests:

    src/app.controller.ts:9:28 - error TS2307: Cannot find module '@lodestar/params' or its corresponding type declarations.

    9     const p = await import('@lodestar/params')

Notes on the repo: it's a plain nestjs project with a controller that dynamically imports the library:

  • git repo: https://github.com/joaorodrigues-consensys/test-lodestart-libs
  • offending line: https://github.com/joaorodrigues-consensys/test-lodestart-libs/blob/main/src/app.controller.ts#L9
  • npm run start && curl http://localhost:6556 runs through controller code, loads the library and returns a valid value
  • npm run test fails with Cannot find module '@lodestar/params' or its corresponding type declarations.

Environment

System:
    OS: Linux 5.18 Pop!_OS 22.04 LTS
    CPU: (16) x64 12th Gen Intel(R) Core(TM) i7-1260P
  Binaries:
    Node: 18.7.0 - ~/.nvm/versions/node/v18.7.0/bin/node
    npm: 8.15.0 - ~/.nvm/versions/node/v18.7.0/bin/npm
  npmPackages:
    jest: 28.1.3 => 28.1.3

joaorodrigues-consensys avatar Aug 10 '22 16:08 joaorodrigues-consensys

You can set diagnostics: false in ts-jest option or use isolatedModules: true to work around the problem. It's something with the type checking which doesn't perform probably comparing to tsc

ahnpnl avatar Aug 10 '22 16:08 ahnpnl

fantastic, both options worked great :+1:

joaorodrigues-consensys avatar Aug 16 '22 09:08 joaorodrigues-consensys