wog*_*and 13 d3.js reactjs jestjs
我正在运行测试
\nimport { render } from '@testing-library/react';\nimport MyComponent from '../../../../components/MyComponent';\n\ntest('renders MyComponent', () => {\n render(<MyComponent />);\n});\nRun Code Online (Sandbox Code Playgroud)\n在使用 d3 的 React 应用程序组件上,导入如下:
\nimport React from 'react';\nimport * as d3 from 'd3';\nRun Code Online (Sandbox Code Playgroud)\n使用命令
\nreact-scripts test\nRun Code Online (Sandbox Code Playgroud)\n这会在 d3 导入时产生错误:
\nJest encountered an unexpected token\n\nThis usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.\n\nBy default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".\n\nHere's what you can do:\n \xe2\x80\xa2 If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.\n \xe2\x80\xa2 To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.\n \xe2\x80\xa2 If you need a custom transformation specify a "transform" option in your config.\n \xe2\x80\xa2 If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.\n\nYou'll find more details and examples of these config options in the docs:\nhttps://jestjs.io/docs/en/configuration.html\n\nDetails:\n\n/Users/wogsland/Projects/sepia/node_modules/d3/src/index.js:1\n({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from "d3-array";\n ^^^^^^\n\nSyntaxError: Unexpected token 'export'\nRun Code Online (Sandbox Code Playgroud)\n我缺少什么?该组件在浏览器中工作正常,只是在最基本的测试中失败了。
\nTie*_*han 10
要转换某些“node_modules”文件,您可以在配置中指定自定义“transformIgnorePatterns”。
从上面的建议中,我们可以告诉 Jest 不要解析node_modules.
在您的jest.config.js文件中,您可以添加以下行。您可以将任何您想要的 ES 模块添加到阵列中。
const esModules = ['d3', 'd3-array', 'other-d3-module-if-needed'].join('|');
module.exports = {
// ...
transformIgnorePatterns: [`/node_modules/(?!${esModules})`],
// ...
};
Run Code Online (Sandbox Code Playgroud)
按照 Tiep Phan 的回答的提示,我将以下内容添加到我的 package.json 文件中:
"jest": {
"transformIgnorePatterns": ["/node_modules/(?!d3|d3-array|internmap|delaunator|robust-predicates)"]
},
Run Code Online (Sandbox Code Playgroud)
对于 D3v7 你可以moduleNameMapper像这样添加笑话:
"moduleNameMapper": {
"d3": "<rootDir>/node_modules/d3/dist/d3.min.js",
"^d3-(.*)$": "<rootDir>/node_modules/d3-$1/dist/d3-$1.min.js"
}
Run Code Online (Sandbox Code Playgroud)