【问题标题】:jest with typescript throws an error when importing a filejest with typescript 在导入文件时抛出错误
【发布时间】:2020-08-28 10:28:32
【问题描述】:

我在打字稿上遇到了开玩笑的问题。

//myprovider.tsx

class MyProvider{
   constructor(){}
   giveMeFive(): int{  return 5;  }
}

export { MyProvider }



// myprovider.test.js

import { MyProvider } from './myprovider';

test('give me five!', () => {
  const myprovider = new MyProvider();
  /// assert
})

我收到以下错误

Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

import { MyProvider } from './myprovider';
       ^

我不确定我缺少什么,我的包裹上有这个

//package.json

  "jest": {
    "transform": {
      ".(ts|tsx)": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "testRegex": "(/tests/.*|\\.(test|spec))\\.(ts|tsx|js)$",
    "moduleFileExtensions": ["ts", "tsx", "js"]
  },



// .babelrc

{
    "presets": [
        "@babel/preset-typescript"
    ]
} 



//jest.config.js

module.exports = {
  preset: 'ts-jest',
  transform: {
    '^.+\\.tsx?$': 'babel-jest',
  },
}

【问题讨论】:

  • 如果您直接导出类而不是像这样在文件底部导出类,是否会出现错误?即 export class MyProvider{ 等...否则我会说更改 export { MyProvider } 以导出默认 MyProvider 并在没有括号的情况下导入您的测试
  • 是的,我做了你的两个建议
  • 这可能是因为您没有在测试中导入 react,顺便说一下,您的文件实际上不是 react 组件,您可以将其设为 ts 文件而不是 tsx。否则在你的测试文件中“import * as React from 'react'”

标签: reactjs typescript jestjs babeljs


【解决方案1】:

确保安装这些软件包:

babel-jest @babel/core @babel/preset-env

您的 babel 配置应如下所示:

  presets: [
    [
      "@babel/preset-env",
      {
        targets: {
          node: "current",
        },
      },
    ],
    "@babel/preset-typescript",
  ]

【讨论】:

  • 这行得通。谢谢!跟进寿,我认为一旦你设置了 tsconfig.js 和 jest.config.js 来将 tsx 转换为 js,你就不需要添加 babel 预设?
  • Tsconfig 在build 步骤中转译您的代码。现在你没有构建你的应用程序。 Babel 将您的代码转换为 Jest。 @gdubs
猜你喜欢
  • 1970-01-01
  • 2019-07-07
  • 2022-01-18
  • 2021-03-03
  • 1970-01-01
  • 2021-12-10
  • 2017-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多