开玩笑遇到了一个意外的令牌+ React Markdown

发布于 2025-02-01 05:24:35 字数 2798 浏览 4 评论 0原文

我会遇到错误(我正在使用React TypeScript),

  ● 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.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • 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:

    export {uriTransformer} from './lib/uri-transformer.js'
    ^^^^^^

    SyntaxError: Unexpected token 'export'

       5 | const Markdown = ({ text, classStyle }: ITextMedia) => (
       6 |   <div className={`${classes.mediaParagraph} ${classStyle ?? ''}`}>
    >  7 |     <ReactMarkdown>{text}</ReactMarkdown>
         |                                             ^
       8 |   </div>
       9 | );
      10 | export default Markdown;

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (components/media/markdown/index.tsx:7:45)

我已经尝试将React Markdown添加到Transform Intrance忽略模式,但是它仍然不起作用

{
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  moduleDirectories: ['node_modules', '<rootDir>/'],
  testEnvironment: 'jest-environment-jsdom',
  moduleNameMapper: {
    'next/router': '<rootDir>/__mocks__/next/router.js',
    '^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
    '^.+\\.(jpg|jpeg|png|gif|webp|avif|svg)$': '<rootDir>/__mocks__/file-mock.js',
  },
  transform: {
    '^.+\\.(js|jsx)$': 'babel-jest'
  },
  transformIgnorePatterns: [
    'node_modules/(?!react-markdown/)'
  ]
}

尝试运行测试文件时,

{
    "presets": [
        "next/babel",
        "@babel/preset-env"
    ],
    "plugins": []
}

我是开玩笑的新手,所以我不确定我是否做错了什么

I'm getting an error when trying to run my test file (I'm using react typescript)

  ● 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.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • 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:

    export {uriTransformer} from './lib/uri-transformer.js'
    ^^^^^^

    SyntaxError: Unexpected token 'export'

       5 | const Markdown = ({ text, classStyle }: ITextMedia) => (
       6 |   <div className={`${classes.mediaParagraph} ${classStyle ?? ''}`}>
    >  7 |     <ReactMarkdown>{text}</ReactMarkdown>
         |                                             ^
       8 |   </div>
       9 | );
      10 | export default Markdown;

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (components/media/markdown/index.tsx:7:45)

I already tried adding the React markdown to the transform ignore patterns, but it still doesn't work

here's my jest.config

{
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  moduleDirectories: ['node_modules', '<rootDir>/'],
  testEnvironment: 'jest-environment-jsdom',
  moduleNameMapper: {
    'next/router': '<rootDir>/__mocks__/next/router.js',
    '^.+\\.module\\.(css|sass|scss)

my babel config:

{
    "presets": [
        "next/babel",
        "@babel/preset-env"
    ],
    "plugins": []
}

I'm new to jest, so I'm not sure if I'm doing something wrong

: 'identity-obj-proxy', '^.+\\.(jpg|jpeg|png|gif|webp|avif|svg)

my babel config:


I'm new to jest, so I'm not sure if I'm doing something wrong

: '<rootDir>/__mocks__/file-mock.js', }, transform: { '^.+\\.(js|jsx)

my babel config:


I'm new to jest, so I'm not sure if I'm doing something wrong

: 'babel-jest' }, transformIgnorePatterns: [ 'node_modules/(?!react-markdown/)' ] }

my babel config:

I'm new to jest, so I'm not sure if I'm doing something wrong

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

你的背包 2025-02-08 05:24:35

jest.config文件中,您需要将以下内容添加到modulenamemapper属性:

“ react-markdown”:“&lt; rootdir&gt;/node_modules/react -markdown/react-markdown.min.js“

如此有效,您的modulenamemapper应该看起来像这样:

  ...
  moduleNameMapper: {
    'next/router': '<rootDir>/__mocks__/next/router.js',
    '^.+\\.module\\.(css|sass|scss)

好运!

: 'identity-obj-proxy', '^.+\\.(jpg|jpeg|png|gif|webp|avif|svg)

好运!

: '<rootDir>/__mocks__/file-mock.js', 'react-markdown': '<rootDir>/node_modules/react-markdown/react-markdown.min.js', }, ...

好运!

In the jest.config file, you need to add the following to the moduleNameMapper attribute:

"react-markdown": "<rootDir>/node_modules/react-markdown/react-markdown.min.js"

So effectively, your moduleNameMapper should really look like this:

  ...
  moduleNameMapper: {
    'next/router': '<rootDir>/__mocks__/next/router.js',
    '^.+\\.module\\.(css|sass|scss)

Good luck!

: 'identity-obj-proxy', '^.+\\.(jpg|jpeg|png|gif|webp|avif|svg)

Good luck!

: '<rootDir>/__mocks__/file-mock.js', 'react-markdown': '<rootDir>/node_modules/react-markdown/react-markdown.min.js', }, ...

Good luck!

八巷 2025-02-08 05:24:35

The following fix in jest.config.js no longer works from version 9.0.0 as they 删除束步

  ...
  moduleNameMapper: {
    'react-markdown': '<rootDir>/node_modules/react-markdown/react-markdown.min.js',
  },
  ...

The following fix in jest.config.js no longer works from version 9.0.0 as they remove the bundle step.

  ...
  moduleNameMapper: {
    'react-markdown': '<rootDir>/node_modules/react-markdown/react-markdown.min.js',
  },
  ...
爱格式化 2025-02-08 05:24:35

仅当您希望忽略错误时,我建议使用此解决方案。

在相关文件夹中创建一个空的模拟文件 - ( empty -mock.ts

const EmptyMock = {};

export default EmptyMock;

,并将其映射到要忽略的导入模块 -

const customJestConfig = {
  moduleNameMapper: {
    //imports to be ignored by jest
    "react-markdown": "<rootDir>/mock/empty-mock.ts",
    "remark-gfm": "<rootDir>/mock/empty-mock.ts",
  },
};

I Recommend this solution only if you want the error to be ignored.

create an empty mock file - (empty-mock.ts in relevant folder)

const EmptyMock = {};

export default EmptyMock;

And map this to import modules to be ignored -

const customJestConfig = {
  moduleNameMapper: {
    //imports to be ignored by jest
    "react-markdown": "<rootDir>/mock/empty-mock.ts",
    "remark-gfm": "<rootDir>/mock/empty-mock.ts",
  },
};
牵你手 2025-02-08 05:24:35

您不仅需要将React-Markdown添加到transformignorepatterns,而且还需要所有纯ESM的依赖项。

运行测试时,您可以在笑话中看到一个依赖项。记住React-Markdown node_modules中的大约。

Details:

/{...}/node_modules/react-markdown/node_modules/comma-separated-tokens/index.js:23

transformignorepatterns中逐个添加一一并再次运行测试以获取下一个错误。

您必须添加React-MarkDown逗号分隔t-tokens等。它将取决于您使用的react-markdown版本。就我而言,是:

"transformIgnorePatterns": [
  "/node_modules/(?!comma-separated-tokens|space-separated-tokens|hast-util-whitespace|property-information|trim-lines|remark-rehype|remark-parse|trough|is-plain-obj|bail|unified|vfile|react-markdown)"
]

You need to add not only react-markdown to the transformIgnorePatterns, but also all its dependencies which are pure ESM.

When running your tests you can see the dependencies one by one in the jest error. Remember about ones inside react-markdown node_modules.

Details:

/{...}/node_modules/react-markdown/node_modules/comma-separated-tokens/index.js:23

Add one by one in the transformIgnorePatterns and run the tests again to get the next error.

You have to add the react-markdown, comma-separated-tokens, and others. It'll depend on the react-markdown version you use. In my case it was:

"transformIgnorePatterns": [
  "/node_modules/(?!comma-separated-tokens|space-separated-tokens|hast-util-whitespace|property-information|trim-lines|remark-rehype|remark-parse|trough|is-plain-obj|bail|unified|vfile|react-markdown)"
]
高速公鹿 2025-02-08 05:24:35

我在环境中也有同样的问题。我们在monorepo中使用nx,并使用pnpm管理包裹。由于pnpm默认情况下缓存模块,因此它不适用于&lt; rootdir&gt;/node_modules/。但是,您也可以在没有此路径的情况下进行,然后它也可以与pnpm一起使用(jest在其文档中还提到&lt; rootdir&gt; < /代码>是可选的):

…
moduleNameMapper: {
  'react-markdown': 'react-markdown/react-markdown.min.js',
},
…

I had the same problem in my environment. We use nx in a monorepo and manage our packages with pnpm. Since pnpm caches modules by default, it does not work with the <rootDir>/node_modules/. However, you can also do without this path, then it works with pnpm as well (jest also mentions in its docs that the usage of <rootDir> is optional):

…
moduleNameMapper: {
  'react-markdown': 'react-markdown/react-markdown.min.js',
},
…
江城子 2025-02-08 05:24:35

当使用React-Markdown v9.0.1时,我也遇到了这一点。在我开始扩展Fernanda Duarte的答案之前,似乎没有任何配置能做到这一点。

似乎由于该模块的新ESM格式,Jest确实有麻烦。我正在使用开玩笑,ESM,打字稿,babel-jest,React以及本文截至本文的其他任何最新模块。

这是我想到的(下),这允许测试干净地进行。您必须设置transformignorepatterns,不仅忽略react-markdown,还忽略其所有依赖性,并在React-Markdown更新自己的依赖关系时进行更新。因此,我已经将它们全部编译成一个阵列,该数组已连接并插入正则ggex,以忽略模式以使其易于阅读。

您不需要使用modulenamemapper或类似的东西使用React-Markdown React-Markdown 。而且,不要费心尝试重新映射react-markdown/react-markdown.min.js,因为v9.x不再包括CommonJS后备。

const esModules = [
  /** react-markdown 9.0.1 */
  'react-markdown',
  'bail',
  'comma-separated-tokens',
  'decode-named-character-reference',
  'devlop/lib/default',
  'estree-util-is-identifier-name',
  'hast-util-.*',
  'html-url-attributes',
  'is-plain-obj',
  'mdast-util-.*',
  'micromark.*',
  'property-information',
  'remark-.*',
  'space-separated-tokens',
  'trim-lines',
  'trough',
  'unified',
  'unist-.*',
  'vfile-message',
  /** react-markdown 8.0.3 */
  'vfile',
].join('|')

// In the config:
{
  ...
  transformIgnorePatterns: [
    // Enable babel transforms for these specific packages. They ship code as es
    // modules only, and must be transpiled in order to run on Node.
    `[/\\\\]node_modules[/\\\\](?!${esModules}).+\\.(js|jsx|mjs|cjs|ts|tsx)

当使用 React-Markdown v9.0.1时,我也遇到了这一点。在我开始扩展Fernanda Duarte的答案之前,似乎没有任何配置能做到这一点。

似乎由于该模块的新ESM格式,Jest确实有麻烦。我正在使用开玩笑,ESM,打字稿,babel-jest,React以及本文截至本文的其他任何最新模块。

这是我想到的(下),这允许测试干净地进行。您必须设置 transformignorepatterns ,不仅忽略 react-markdown ,还忽略其所有依赖性,并在React-Markdown更新自己的依赖关系时进行更新。因此,我已经将它们全部编译成一个阵列,该数组已连接并插入正则ggex,以忽略模式以使其易于阅读。

您不需要使用 modulenamemapper 或类似的东西使用React-Markdown React-Markdown 。而且,不要费心尝试重新映射 react-markdown/react-markdown.min.js ,因为v9.x不再包括CommonJS后备。

, ], ... }

I too encountered this when using react-markdown v9.0.1. It seemed no amount of configuring did the trick until I started expanding on Fernanda Duarte's answer, using some inspiration from another answer (that I can't find right now, apologies to its author).

It seems that because of the new ESM format of this module, jest really has trouble with. I'm using Jest, ESM, Typescript, babel-jest, React, and whatever other latest modules there are as of the time of this post.

Here's what I came up with (below), which allows the tests to run cleanly. You must set up the transformIgnorePatterns to ignore not only react-markdown but all of its dependencies, and update them whenever react-markdown updates its own dependencies. So I've compiled them all into an array that's joined up and inserted into the RegEx for the ignore patterns to make this easier to read.

You don't need to stub-out react-markdown using moduleNameMapper or anything like that. And don't bother trying to remap react-markdown/react-markdown.min.js either, as v9.x doesn't include a CommonJS fallback any more.

const esModules = [
  /** react-markdown 9.0.1 */
  'react-markdown',
  'bail',
  'comma-separated-tokens',
  'decode-named-character-reference',
  'devlop/lib/default',
  'estree-util-is-identifier-name',
  'hast-util-.*',
  'html-url-attributes',
  'is-plain-obj',
  'mdast-util-.*',
  'micromark.*',
  'property-information',
  'remark-.*',
  'space-separated-tokens',
  'trim-lines',
  'trough',
  'unified',
  'unist-.*',
  'vfile-message',
  /** react-markdown 8.0.3 */
  'vfile',
].join('|')

// In the config:
{
  ...
  transformIgnorePatterns: [
    // Enable babel transforms for these specific packages. They ship code as es
    // modules only, and must be transpiled in order to run on Node.
    `[/\\\\]node_modules[/\\\\](?!${esModules}).+\\.(js|jsx|mjs|cjs|ts|tsx)

I too encountered this when using react-markdown v9.0.1. It seemed no amount of configuring did the trick until I started expanding on Fernanda Duarte's answer, using some inspiration from another answer (that I can't find right now, apologies to its author).

It seems that because of the new ESM format of this module, jest really has trouble with. I'm using Jest, ESM, Typescript, babel-jest, React, and whatever other latest modules there are as of the time of this post.

Here's what I came up with (below), which allows the tests to run cleanly. You must set up the transformIgnorePatterns to ignore not only react-markdown but all of its dependencies, and update them whenever react-markdown updates its own dependencies. So I've compiled them all into an array that's joined up and inserted into the RegEx for the ignore patterns to make this easier to read.

You don't need to stub-out react-markdown using moduleNameMapper or anything like that. And don't bother trying to remap react-markdown/react-markdown.min.js either, as v9.x doesn't include a CommonJS fallback any more.

, ], ... }
风渺 2025-02-08 05:24:35

为了在v9+中解决此问题,我们创建了一个模拟,该模拟仍然使我们能够验证传递给reactmarkdown的内容已渲染到屏幕上(注意:示例代码在Typescript中)。

import { ReactNode } from "react";

interface ChildrenProps {
    children: ReactNode;
}

function ReactMarkdownMock({ children }: ChildrenProps) {
    return <p>{children}</p>;
}

export default ReactMarkdownMock;

然后在jest.config.js中注册。

…
moduleNameMapper: {
  'react-markdown': '"<rootDir>/mock/ReactMarkdownMock.tsx',
},
…

To workaround this issue in v9+ we created a mock that still allowed us to verify that the content passed to ReactMarkdown was rendered to the screen (Note: example code is in Typescript).

import { ReactNode } from "react";

interface ChildrenProps {
    children: ReactNode;
}

function ReactMarkdownMock({ children }: ChildrenProps) {
    return <p>{children}</p>;
}

export default ReactMarkdownMock;

This was then registered in jest.config.js:

…
moduleNameMapper: {
  'react-markdown': '"<rootDir>/mock/ReactMarkdownMock.tsx',
},
…
愿得七秒忆 2025-02-08 05:24:35

对于@uiw/react-markdown-preview 插件,我也有同样的问题。

我唯一可以做的只会在 modulenamemapper 内部添加它。

"react-markdown-preview": "<rootDir>/node_modules/@uiw/react-markdown-preview/dist/markdown.min.js"

I have the same problem for @uiw/react-markdown-preview plugin.

The only thing I can do it just add this under moduleNameMapper inside package.json

"react-markdown-preview": "<rootDir>/node_modules/@uiw/react-markdown-preview/dist/markdown.min.js"
短叹 2025-02-08 05:24:35

它在代码中是一个简单的修复程序,只需将导入语句

import ReactMarkdown from 'react-markdown';

import ReactMarkdown from 'react-markdown/react-markdown.min';

Its a simple fix in the code, just change the import statement from

import ReactMarkdown from 'react-markdown';

to

import ReactMarkdown from 'react-markdown/react-markdown.min';
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文