首页 > 解决方案 > 使用打字稿,反应和开玩笑设置一个新项目,我遇到了 SyntaxError: Unexpected token '<'

问题描述

我正在从头开始建立一个新项目。该项目是使用故事书和笑话进行测试的打字稿。我在toMatchSnapshot()反应组件上运行断言时遇到问题。

这是我的index.test.tsx

import React from 'react';
import renderer from 'react-test-renderer';
import {Button} from '../index';

it('renders correctly', () => {
    const tree = renderer.create(<Button/>).toJSON();
    expect(tree).toMatchSnapshot();
});

我的jest.config.ts

import type {Config} from '@jest/types';

const config: Config.InitialOptions = {
    verbose: true,
    collectCoverageFrom: [
        'src/components/**/*.{ts,tsx}',
    ],
    coverageDirectory: 'reports/coverage/unit',
    coverageThreshold: {
        global: {
            branches: 90,
            functions: 90,
            lines: 90,
            statements: 90,
        },
    },
    transform: {'^.+\\.(ts|tsx)$': 'ts-jest'},
    testMatch: ['**/*.test.*'],
    coverageProvider: 'v8',
};

export default config;

我的tsconfig.json

{
  "compilerOptions": {
    "sourceMap": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "jsx": "preserve",
    "baseUrl": "./src",
    "paths": {
      "@/*": [
        "./*"
      ]
    }
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "**/*.ts",
    "**/*.tsx"
  ]
}

我的package.json

{
  "name": "project-name",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "type-check": "tsc",
    "lint": "eslint src --ext .tsx",
    "lint:fix": "npm run lint -- --fix",
    "test": "jest",
    "test:watch": "npm run test -- --watch",
    "test:coverage": "npm run test -- --coverage",
    "storybook": "start-storybook -p 6006",
    "build-storybook": "build-storybook"
  },
  "dependencies": {
    "@storybook/react": "^6.3.7",
    "bootstrap": "^5.1.0",
    "classnames": "^2.3.1",
    "prop-types": "^15.7.2",
    "react": "^17.0.2",
    "react-bootstrap": "^2.0.0-beta.2",
    "react-dom": "^17.0.2",
    "storybook-addon-responsive-views": "^2.3.0"
  },
  "devDependencies": {
    "@storybook/addon-actions": "^6.3.7",
    "@storybook/addon-docs": "^6.3.7",
    "@storybook/addon-essentials": "^6.3.7",
    "@storybook/addon-links": "^6.3.7",
    "@storybook/builder-webpack5": "^6.3.7",
    "@storybook/manager-webpack5": "^6.3.7",
    "@types/jest": "^27.0.1",
    "@types/node": "^16.6.1",
    "@types/react": "^17.0.18",
    "@types/react-dom": "^17.0.9",
    "@types/react-test-renderer": "^17.0.1",
    "@typescript-eslint/eslint-plugin": "^4.29.2",
    "@typescript-eslint/parser": "^4.29.2",
    "eslint": "^7.32.0",
    "eslint-config-airbnb": "^18.2.1",
    "eslint-plugin-import": "^2.24.0",
    "eslint-plugin-jest": "^24.4.0",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-react": "^7.24.0",
    "eslint-plugin-react-hooks": "^4.2.0",
    "husky": "^7.0.1",
    "jest": "^27.0.6",
    "node-sass": "^6.0.1",
    "node-sass-magic-importer": "^5.3.2",
    "resolve-url-loader": "^4.0.0",
    "sass-loader": "^12.1.0",
    "ts-jest": "^27.0.5",
    "ts-node": "^10.2.0",
    "typescript": "^4.3.5"
  },
  "husky": {
    "hooks": {
      "pre-commit": "npm run lint"
    }
  }
}

当我运行测试时,结果如下:

 FAIL  src/components/buttons/button/__tests__/index.test.tsx
  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • 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.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /Users/marco/Code/project-name/src/components/buttons/button/__tests__/index.test.tsx:19
        const tree = react_test_renderer_1.default.create(<index_1.Button />).toJSON();
                                                          ^

    SyntaxError: Unexpected token '<'

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1479:14)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        4.003 s
Ran all test suites.


标签: reactjstypescriptjestjs

解决方案


修复非常简单。我必须在 tsconfig.json 中将“jsx”键设置为“react”而不是“preserve”。在这里找到答案:https ://github.com/vercel/next.js/issues/8663


推荐阅读