node.js - 在 node_modules 错误中带有 ES 模块的 Jest Typescript - 必须使用导入来加载 ES 模块 :

标签 node.js typescript jestjs es6-modules

我正在尝试为仅导出 ES 模块的 3rd 方包编写一个简单的 Jest 测试。它是 http 的包装器服务器。
这是我设置的测试仓库(只需运行 yarn && yarn jest 即可重现):https://github.com/jamesopti/hocuspocus-testing
无论我试验什么配置,在尝试运行它时仍然会出现此错误:

 Must use import to load ES Module: /Users/j/hocuspocus-testing/node_modules/@hocuspocus/server/dist/hocuspocus-server.esm.js

    > 1 | import { Server, Hocuspocus } from '@hocuspocus/server'
        | ^
      2 | import * as request from 'supertest'
      3 |
      4 | describe('Server (e2e)', () => {
我已经尝试过的东西:
  • ES 模块的 Jest 说明:https://jestjs.io/docs/ecmascript-modules
  • 在 Jest 配置中使用 transformIgnorePatterns
  • transformIgnorePatterns: ['node_modules/(?!@hocuspocus/)']

  • 通过 babel-jest 使用 Babel
  • 将 Jest 配置中的转换设置修改为 '^.+\.jsx?$': 'babel-jest', '^.+\.tsx?$': 'ts-jest'
  • 遇到错误 You appear to be using a native ECMAScript module configuration file, which is only supported when running Babel asynchronously.
  • 使用 .babel.config.js 而不是 .babelrc.js


  • 有什么想法我在这里想念的吗?我认为这很简单
    [编辑 1] - 新增 tsconfig.json和一个工作 src/index.ts文件到 the example repo .

    最佳答案

    因此,对于仍然遇到此问题的任何人,文档的这一部分中解释了 ESM 配置:
    https://kulshekhar.github.io/ts-jest/docs/guides/esm-support

    {
      // [...]
      "jest": {
        "extensionsToTreatAsEsm": [".ts"],
        "globals": {
          "ts-jest": {
            "useESM": true
          }
        }
      }
    }
    

    关于node.js - 在 node_modules 错误中带有 ES 模块的 Jest Typescript - 必须使用导入来加载 ES 模块 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68520619/

    相关文章:

    javascript - 使用 Jest 和 Enzyme 测试 React 组件中的去抖动功能

    jestjs - 尽管在 package.json 中进行了配置,但 monorepo 中应用程序的 Nestjs e2e 测试无法通过 jest 解析从库中导入的 @app

    javascript - Mongoose 自定义密码验证

    node.js - 通过 websocket 进行音频流传输

    reactjs - 如何在 ReactJS 中使用 mobx 组织 typescript

    typescript - 如何将接口(interface)包装在对象中,同时在 TypeScript 中导出它?

    javascript - Node js : Uncaught error 中未定义 mustache 错误

    javascript - 预期等于结果时出现不可变的 Chai 断言错误

    typescript - TypeScript 中的通用对象数组

    unit-testing - 在 Jest 中模拟模块时如何断言调用默认导出函数?