Javascript 开玩笑可以';t使用HOC from js文件,但可以正确使用HOC from tsx文件

Javascript 开玩笑可以';t使用HOC from js文件,但可以正确使用HOC from tsx文件,javascript,reactjs,jestjs,Javascript,Reactjs,Jestjs,从tsx文件导入HOC时,一切正常。但是,当我将扩展更改为js时,我看到一个Jest错误: Jest遇到了意外的标记。这通常意味着您正试图导入Jest无法解析的文件,例如,它不是纯JavaScript By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules". Here's what you can do:

从tsx文件导入HOC时,一切正常。但是,当我将扩展更改为js时,我看到一个Jest错误:

Jest遇到了意外的标记。这通常意味着您正试图导入Jest无法解析的文件,例如,它不是纯JavaScript

  By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
  Here's what you can do:
   • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
   • If you need a custom transformation specify a "transform" option in your config.
   • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
My jest.config.js:

module.exports = {
  automock: false,
  preset: 'ts-jest/presets/js-with-babel',
  setupTestFrameworkScriptFile: '<rootDir>/_internals/jest/setup.js',
  moduleNameMapper: {
    '\\.(less|svg|png|css|pdf|woff|woff2)$': 'identity-obj-proxy',
    ...mappers,
  },
  testPathIgnorePatterns: ['/node_modules/', '/lib/', '/dist/', '/.tmp/', '/git/'],
  testMatch: null,
  testRegex: '/tests/[a-zA-z-_]+\\.spec\\.(tsx|ts)$',
  moduleDirectories: ['node_modules'],
  moduleFileExtensions: ['js', 'json', 'ts', 'tsx'],
};
如何解决此问题?

您可以在文档中看到,您当前使用的预设将允许babel处理
.js
文件

ts jest/presets/js with babel:类型脚本文件将由ts jest处理,JavaScript文件将由babel jest处理

因此,你应该:

添加@babel/预设反应 这将转换所有jsx

.babelrc
{
  "presets": ["@babel/preset-react"]
  "env" : {
    "test" : {
      "plugins": ["transform-es2015-modules-commonjs"]
    }
  }
}

{
 //...
 allowJs: true
}

将ts jest/presets/js与ts一起使用 如果需要,请添加

tsconfig.json
{
  "presets": ["@babel/preset-react"]
  "env" : {
    "test" : {
      "plugins": ["transform-es2015-modules-commonjs"]
    }
  }
}

{
 //...
 allowJs: true
}

Edit:如果您的应用程序在myHOC为
.js
时工作,您可能应该选择第二个选项

,因为您正在使用
ts jest/presets/js与babel
共享您的babel可能会很有用configuration@teneff”他补充道
{
 //...
 allowJs: true
}