Jest Babel TypeScript类类型参数意外令牌

问题描述

我遇到了Jest的问题,它无法理解类类型参数。

Example Repo

Error output

SyntaxError: /Users/john/dev/webpack-test/src/__tests__/utils.test.js: Unexpected token (18:40)

      16 | describe('new Drawer()',() => {
      17 |   it('should add and remove socks',() => {
    > 18 |     const sockDrawer = new Drawer<Sock>();

我正在使用TypeScript游乐场中的类通用示例。

Example Code

export class Drawer<ClothingType> {
  contents: ClothingType[] = [];

  add(object: ClothingType) {
    this.contents.push(object);
  }

  remove() {
    return this.contents.pop();
  }
}

export interface Sock {
  color: string;
}

export interface TShirt {
  size: "s" | "m" | "l";
}

然后我有一个正在使用它的测试。我也在我的React应用程序中调用它,以确保它可以在那里编译并成功完成。

Test Code

it('should add and remove socks',() => {
  const sockDrawer = new Drawer<Sock>();

  sockDrawer.add({ color: "white" });
  expect(sockDrawer.contents).toEqual([{ color: 'white' }]);
  const mySock = sockDrawer.remove();
  expect(sockDrawer.contents.length).toEqual(0);
});

App Code编译正常。

Babel Config


{
  "env": {
    "test": {
      "presets": [
        [
          "@babel/preset-env",{
            "targets": {
              "node": "10.17.0"
            }
          }
        ],"@babel/preset-react","@babel/preset-typescript"
      ],"plugins": [
        "@babel/plugin-transform-runtime",["@babel/plugin-proposal-class-properties",{ "loose": true }]
      ]
    }
}

这里的任何帮助将不胜感激。谢谢!

解决方法

解决此问题的方法是将以下配置添加到 Babel 配置中的 presets

[
    "@babel/preset-typescript",{
        "isTSX": true,"allExtensions": true,"jsxPragma": "react","onlyRemoveTypeImports": true
    }
]