javascript - ts-jest 无法运行 tsx 测试文件,因为模块的 js 文件中的“Import”
我正在尝试使用ts-jest来运行一个 tsx 测试文件form.spec.tsx。
form.spec.tsx 导入了 React Quill 编辑器及其中的一些插件。
如何绕过来自名为 quill-mention 的插件的 SyntaxError: Unexpected identifier 错误,该插件导入了 Quill?该模块涉及 form.spec.tsx。
我已经在 jest 配置的 transformIgnorePatterns 字段中添加了 [",但这个问题仍然存在于 /node_modules/quill-mention/src/quill.mention.js
● Test suite failed to run
/home/web/node_modules/quill-mention/src/quill.mention.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Quill from 'quill';
^^^^^
SyntaxError: Unexpected identifier
1 | import React from "react"
> 2 | import "quill-mention";
| ^
form.spec.tsx:
import {render, RenderResult, waitForElement} from "react-testing-library";
import ReactQuill, {Quill} from 'react-quill';
import "quill-mention";
const renderResult = render(
<ReactQuill
modules={
{
mention: {
allowedChars: /^[A-Za-z\sÅÄÖåäö]*$/,
mentionDenotationChars: ["@", "#"],
},
}
/>
);
package.json
"jest": {
"transform": {
"^.+\\.tsx?$": "ts-jest"
},
"globals": {
"ts-jest": {
"tsConfig": "tsconfig.jest.json"
},
"window": {}
},
"testRegex": "(/watch/web/__tests__/.*|(\\.|/)(test|spec))\\.(jsxxxx?|tsx?)$",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
],
"modulePaths": [
"<rootDir>"
],
"moduleNameMapper": {
".+\\.(css|styl|less|sass|scss)$": "identity-obj-proxy",
".+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/FileMock.js"
},
"transformIgnorePatterns": [
"<rootDir>/node_modules/"
]
}
tsconfig.jest.json:
{
"compilerOptions": {
"jsx": "react",
"module": "commonjs",
"target": "es6",
"moduleResolution": "node",
"removeComments": true,
"allowSyntheticDefaultImports": true,
"noImplicitAny": false,
"experimentalDecorators": true,
"noLib": false,
"declaration": false,
"emitDecoratorMetadata": true,
"lib": ["es6", "dom"],
"types": ["jest","reflect-metadata"],
"inlineSources":true,
"skipLibCheck": true,
"esModuleInterop": true
},
"exclude": [
"node_modules"
]
}
有人说 allowJs: true 可以解决这个问题,但它不起作用。我的所有测试都失败了,提示 JavaScript 堆内存不足。
答案#1
问题是 Jest 没有转换那个文件。在普通的 JS 中,import 是不合法的。你需要配置 Jest,使它能够转换那个文件。
首先,将 transform 更改为也处理扩展名为 js 或 jsx 的文件(除了 ts 文件之外:)
"jest": {
"transform": {
"^.+\\.(ts|js)x?$": "ts-jest"
},
接下来你需要将该目录加入白名单,这样 Jest 才会对其进行转换。这会跳过对 node_modules 中所有文件的转换,除了 quill-mention 目录。
"transformIgnorePatterns": [
"<rootDir>/node_modules/(?!(quill-mention)/)"
]
这应该可以解决与 quill-mention 相关的问题。现在它应该会因为 ReferenceError: MutationObserver is not defined 而失败,这是一个不同的问题,与 Jest 使用的 JSDom 环境有关。你可以在这里阅读如何解决这个问题:
使用 Jest 测试 MutationObserver
你也可能想考虑改用 babel-jest + @babel/preset-typescript,而不是使用 ts-jest。
