【问题标题】:Using CKEditor with Angular and Jest将 CKEditor 与 Angular 和 Jest 一起使用
【发布时间】:2021-03-04 12:05:15
【问题描述】:

我在我的 Angular 10 应用程序中使用 CKEditor5。经过漫长而痛苦的集成过程,CKEditor 在应用程序中完美运行。该应用程序的结构是一个 nx monorepo,如果这有影响的话。

但是,我现在无法为我的应用运行某些单元测试。任何使用 CKeditor 的组件(目前大约 5 个组件)的单元测试现在都会失败,并出现以下错误:

C:\path\to\my\repo\node_modules@ckeditor\ckeditor5-watchdog\src\editorwatchdog.js:12

从'lodash-es'导入{throttle,cloneDeepWith,isElement};

^^^^^^

SyntaxError: 不能在模块外使用 import 语句

看来我需要使用 Babel 来转换 editorwatchdog.js 中的导入,以便 Jest 可以理解它们。为了解决这个问题,我安装了@babel/core 7.13.8、@babel/preset-env 7.13.9 和 babel-jest 26.6.3(注意,我已经安装了 jest 26.2.2)

我在项目的根目录下添加了一个 babel.config.js 文件,其中仅包含以下内容:

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

最后,我更新了我的 jest.config.js 根文件以包含 transform 和 transformIgnorePatterns 键:

module.exports = {
  transform: {},
  transformIgnorePatterns: "\\\\/node_modules\\\\/(?!@ckeditor).+\\.(js|jsx|ts|tsx)$",
  projects: [
    ... // all my libs and apps
  ]
}

(注意:我也尝试将 transform 和 transformIgnorePatterns 添加到 package.json)

但是当我使用上述更改运行测试时,我仍然看到与以前相同的错误消息。显然我错过了什么,但是什么?

最终结果是我需要 Babel 仅转换 @ckeditor 文件,并且仅在运行单元测试时。

【问题讨论】:

    标签: jestjs babeljs angular10 ckeditor5 babel-jest


    【解决方案1】:

    我正在使用 Jest 来测试带有 CKEditor 5 组件的 React 应用程序。

    您收到此错误是因为Jest does not support fully ECMAScript modules

    首先,您需要告诉 Jest 转换 CKEditor 5 代码:

    // jest.config.ts
    export default {
      // ...
      transformIgnorePatterns: [
        '\\\\/node_modules\\\\/(?!@ckeditor).+\\.(js|jsx|ts|tsx)$',
        '\\.pnp\\.[^\\/]+$'
      ],
    }
    

    这将转换 CKEditor5 模块,但您会遇到 SVG 的类似错误:

    SyntaxError: Unexpected token '

    或 CSS 文件:

    .ck.ck-占位符,

    ^

    SyntaxError: Unexpected token '.'

    这是因为 CKEditor 5 使用 webpack 的 file-loader 来加载 SVG 文件。这可以通过mocking any SVG or CSS file 克服:

    // jest.config.ts
    export default {
      // ...
      moduleNameMapper: {
        '\\.(svg|css)$': '<rootDir>/test/__mocks__/fileMock.js',
      },
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-31
      • 2018-04-04
      • 2020-02-24
      • 1970-01-01
      • 2016-10-06
      • 2018-08-09
      • 2016-11-25
      • 1970-01-01
      相关资源
      最近更新 更多