reactjs - 导入文件时用 typescript 开 Jest 会引发错误

标签 reactjs typescript jestjs babeljs

我在 typescript 上 Jest 话时遇到问题。

//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',
  },
}

最佳答案

确保安装这些软件包:

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

你的 babel 配置应该如下所示:

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

关于reactjs - 导入文件时用 typescript 开 Jest 会引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61754138/

相关文章:

javascript - react 语法错误: Unexpected Token at =

javascript - react-google-maps fitBounds 和 panToBounds 不会缩放 map

reactjs - React 事件处理程序上的控制台日志语句导致合成事件警告

javascript - 创建通用自定义组件 React

reactjs - 如何编写测试用例来检查函数是否返回确切的组件

javascript - 如何更新这样的嵌套状态?

typescript - vue 类组件 : how to create and initialize reflective data

jquery - 使用Typescript(Angular 8)一个接一个地旋转木马

reactjs - 如何使用 JEST、Enzyme 在 React 中测试自定义钩子(Hook)?

javascript - 如何配置 Jest 快照位置