我正在尝试为使用的第 3 方包编写一个简单的玩笑测试,该包仅导出 ES 模块。它是
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
文件到 示例存储库。
因此,对于仍然遇到此问题的任何人,本部分文档中解释了 ESM 配置:
https://kulshekhar.github.io/ts-jest/docs/guides/esm-support
{
// [...]
"jest": {
"extensionsToTreatAsEsm": [".ts"],
"globals": {
"ts-jest": {
"useESM": true
}
}
}
}
2023 年 1 月:ES2022、TypeScript 4.9.4、jest 29.3.1、ts-jest 29.0.3
经过两个小时的挫折后,这对我有用。 我在
jest.config.ts
中使用了这个配置:
import type { JestConfigWithTsJest } from 'ts-jest'
const config: JestConfigWithTsJest = {
extensionsToTreatAsEsm: ['.ts'],
verbose: true,
preset: 'ts-jest/presets/default-esm',
testEnvironment: 'node',
transform: {
'^.+\\.(ts|tsx)?$': ['ts-jest', { useESM: true }]
},
testPathIgnorePatterns: ['./dist']
}
export default config
将
test
中的 package.json
脚本更改为:
我用
。使用 npm 更改为pnpm
, 或npx jest
用纱线yarn exec
...
"scripts": {
...
"test": "NODE_OPTIONS=--experimental-vm-modules pnpm exec jest",
...
}
...
tsconfig.json
:
{
"compilerOptions": {
"rootDirs": ["src"],
"outDir": "dist",
"lib": ["ES2022"],
"target": "ES2022",
"module": "ES2022",
"composite": true,
"moduleResolution": "node",
"declaration": true,
"declarationMap": true,
"incremental": true,
"esModuleInterop": true,
"types": ["jest", "node", "@types/jest"],
"sourceMap": true
},
"ts-node": {
"esm": true,
"experimentalSpecifierResolution": "node"
},
"include": ["./src/**/*", "./tests/**/*"]
}
请参阅此(相当混乱)文档以供参考: https://kulshekhar.github.io/ts-jest/docs/guides/esm-support/
您没有指定
tsconfig.json
的
module
文件。因此,它使用默认值,将所有模块转换为 CommonJS
语法,该语法使用 require
。
如果您实际查看
dist/hocuspocus-server.esm.js
,您应该会看到它在 ESM 导入语法上使用 require
。
我的 svelte 应用程序和测试也遇到同样的问题。我最终追踪到它在我的根文件夹中有一个
jest.config.js
和一个jest.config.json
。看来 jest 没有自动配置文件解析,并且使用默认配置而不是我指定的配置。
尽管我很不愿意给出“使用其他东西”类型的答案,但我还是会这样做,即使它可能无法直接回答原来的问题。
但是,它确实回答了这个问题:“如何在使用 Jest 语法的同时轻松测试具有 ESM 依赖项的 TypeScript 文件?”
在尝试了各种
jest.config.js
选项之后,并从其中一些答案中汲取了想法,我最终做到了:
npm install -D vitest
...而且,这一切都奏效了。没有
jest.config.js
文件。不会弄乱任何其他依赖项。
我必须做的唯一改变是导入一些与测试相关的函数,而 Jest 则不需要这些函数:
import { expect, describe, it } from "vitest";
除此之外,很容易忘记我不只是使用 Jest。
更多详细信息请参见:https://vitest.dev/guide/