首页 > 解决方案 > 如何编写 Jest transformIgnorePatterns

问题描述

我有这个例外

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".

    Here's what you can do:
     • 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/en/configuration.html

    Details:

    C:\Code\SPFx\BCO\node_modules\@microsoft\sp-core-library\lib\index.js:11
    export { default as _BrowserDetection } from './BrowserDetection';
    ^^^^^^

    SyntaxError: Unexpected token export

      19 | } from 'office-ui-fabric-react/lib/Utilities';
      20 | import { IUserProvider } from "../UserProviders/IUserProvider";
    > 21 | import {
         | ^
      22 |   Environment,
      23 |   EnvironmentType
      24 | } from '@microsoft/sp-core-library';

      at ScriptTransformer._transformAndBuildScript (node_modules/jest/node_modules/jest-runtime/build/script_transformer.js:403:17)
      at Object.<anonymous> (src/webparts/BCO/components/EmployeeSelector/EmployeeSelector.tsx:21:1)
      at Object.<anonymous> (src/webparts/BCO/components/FieldMapping/FieldMapping.tsx:13:1)

并在 config.json 中尝试了这些 transformIgnorePatterns 表达式

"transformIgnorePatterns": [
  "\\node_modules\\@microsoft\\sp-dialog",
  "\\node_modules\\@microsoft\\sp-core-library",
  "node_modules/(?!sp-core-library)",
  "node_modules/(?!@microsoft/sp-core-library)"
],

他们都没有工作。我在 Windows 10 上运行它,所以我也尝试了这种格式

标签: jestjs

解决方案


transformIgnorePatterns意味着如果测试路径匹配任何模式,它将不会被转换。

注意:不要拆分多行

开玩笑将node_modules默认忽略所有。

所以你必须这样写:

"transformIgnorePatterns": [
  // all exceptions must be first line
  "/node_modules/(?!@microsoft/sp-core-library|sp-dialog|other_libs_need_transform)"
],

推荐阅读