将 CKEditor 与 Angular 和 Jest 结合使用

问题描述

我在我的 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 };

^^^^^^^

语法错误:不能在模块外使用导入语句

看来我需要使用 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 文件,并且只在运行单元测试时。

解决方法

我正在使用 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 错误:

语法错误:意外标记“

或 CSS 文件:

.ck.ck-占位符,

^

语法错误:意外的标记“.”

这是因为 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',},}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...