简体   繁体   English

Jest 遇到了意外的令牌

[英]Jest encountered an unexpected token

I am new to unit testing.我是单元测试的新手。 I use react typescript I wrote a unit test that fails at the first line, because of import .我使用react typescript我写了一个单元测试,但由于import而在第一行失败了。 How can I config this to work?我怎样才能配置这个工作?

error :错误

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.

Details:

/app/node_modules/axios/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js';                                                                                  ^^^^^^

SyntaxError: Cannot use import statement outside a module

> 1 | import {AxiosError, AxiosInstance, AxiosResponse} from "axios";

config : package.json配置:package.json

"devDependencies": {
        "@babel/core": "^7.20.7",
        "@testing-library/dom": "^8.19.1",
        "@testing-library/react": "^13.4.0",
        "@types/testing-library__react": "^10.2.0",
        "autoprefixer": "^10.4.13",
        "babel-jest": "^29.3.1",
        "eslint": "8.30.0",
        "eslint-config-react-app": "^7.0.1",
        "jest": "^29.3.1",
        "jest-environment-jsdom": "^29.3.1",
        "postcss": "^8.4.20",
        "postcss-import": "^15.1.0",
        "prettier": "^2.8.1",
        "prettier-plugin-tailwindcss": "^0.2.1",
        "react-test-renderer": "^18.2.0",
        "tailwindcss": "^3.2.4",
        "ts-jest": "^29.0.3"
    }

balel.config.js: balel.config.js:

module.exports = {
    presets: [
        [
            '@babel/preset-env',
            {
                targets: {
                    node: 'current',
                },
            },
        ],
    ],
};

jest.config.js jest.config.js

/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
    preset: "ts-jest",
    testEnvironment: "jsdom",
    transform: {
        '^.+\\.ts?$': 'ts-jest',
    },
    transformIgnorePatterns: ['<rootDir>/node_modules/'],
};

The pattern: '^.+\\.ts?$' is wrong.模式: '^.+\\.ts?$'是错误的。

Fix使固定

It should be: '^.+\\.tsx?$' .它应该是: '^.+\\.tsx?$'

More更多的

There might be other issues as well.可能还有其他问题。 Recommend creating a new project and comparing yours with that.建议创建一个新项目并将您的项目与该项目进行比较。

From the official docs: https://kulshekhar.github.io/ts-jest/docs/getting-started/options来自官方文档: https://kulshekhar.github.io/ts-jest/docs/getting-started/options

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM