javascript - 使用最新版本的 d3-path 配置 jest
问题描述
出于某种原因,我的笑话配置不适用于最新版本的d3-path@3.0.1
. 它适用于 version 2.0.0
。我想这与d3-path
切换到 ESM 有关,但我已经在自己的代码中使用 ES6,所以我不明白为什么它突然不再工作了。我安装了以下软件包:
"dependencies": {
"d3-path": "^3.0.1"
},
"devDependencies": {
"@babel/core": "^7.15.8",
"@babel/preset-env": "^7.15.8",
"babel-jest": "^27.3.1",
"jest": "^27.3.1"
}
我的babel.config.js
:
module.exports = {
presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
};
我的index.js
:
import { path } from 'd3-path'
export default () => path()
测试文件:
import fn from '../src/index.js'
describe('test', () => {
it('works', () => {
fn()
expect(2 + 2).toBe(4)
})
})
错误信息:
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export {default as path} from "./path.js";
^^^^^^
SyntaxError: Unexpected token 'export'
> 1 | import { path } from 'd3-path'
重现:
git clone https://github.com/luucvanderzee/jest-problem.git
cd jest-problem
npm i
npm run test
// The test runs without failure- this is because we're currently still using d3-path@2.0.0
npm uninstall d3-path && npm install d3-path // (upgrade to d3-path@3.0.1)
npm run test
// Now the test fails.
我应该如何配置 jest 和/或 babel 来解决这个问题?
编辑:
我已经尝试了以下(来自开玩笑文档的这个页面):
- 使用以下内容创建
jest.config.js
文件:
module.exports = {
transform: {}
}
- 将我的
"test"
命令从更改"jest"
为"node --experimental-vm-modules node_modules/jest/bin/jest.js"
这给了我另一个错误:
/home/luuc/Projects/javascript/jest-problem/test/test.test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import fn from '../src/index.js'
^^^^^^
SyntaxError: Cannot use import statement outside a module
我也不明白是什么意思
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
不就是模块没有改造的问题吗?添加忽略模式不仅会导致模块不被转换吗?
解决方案
问题
发生错误是因为默认情况下jest
不发送node_modules
要被 babel 转换的内容。
的以下输出行npm run test
指示解决问题的一种方法:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
解决方案
jest
应该更新配置以指示它转换依赖关系中ESM
存在的代码。d3-path
为此,请将以下内容添加到jest.config.js
项目根目录中的文件中:
module.exports = {
transformIgnorePatterns: ['node_modules/(?!(d3-path)/)']
}
npm run test
之后运行良好。
该transformIgnorePatterns
选项在此处记录。
编辑 - 包括更多模块
为了包含以 开头的所有模块d3
,可以使用以下语法:
transformIgnorePatterns: ['/node_modules/(?!(d3.*)/)']
推荐阅读
- c# - 如何使用 Console.SetCursorPosition c# 绘制对角线?
- javascript - 添加键盘快捷键
- xml - 未封闭的 XML 标记
- php - xml 的 CURL 命令无法通过 php 脚本发送
- amazon-web-services - 从 API Gateway 触发 CodeBuild 时出现 com.amazon.coral.service#UnknownOperationException
- xpath - 如何使用 IMPORTXML 仅导入表中的有限范围,而不是整个表?
- json - 运行 ng serve 时出现以下错误
- html - 如何用图像填充其余的 div 高度?
- javascript - 以参数名称传递表单参数并将“&”替换为“/”
- javascript - 有没有一种简单的方法可以从 vuejs 获取所有数据?