如何让Jest支持在TypeScript文件中导入HTML文件?
问题:Jest测试TypeScript Web Component时无法正确导入HTML文件作为字符串
项目背景
我有一个基于Rollup和TypeScript构建的TypeScript Web Component项目,组件示例代码如下:
import HTML from './project-build-info.html'; import CSS from './project-build-info.scss'; export class ProjectBuildInfoWebComponent extends HTMLElement { elements:ElementsObject; constructor() { super(); this.initWebComponent(); } initWebComponent() { const shadowRoot = this.attachShadow({ mode: 'open' }); const html = `<style>${CSS}</style>` + '\n' + HTML; const element = document.createElement('template'); element.innerHTML = html; shadowRoot.appendChild(element.content.cloneNode(true)); } }
组件的HTML代码单独存放在独立文件中,导入后插入DOM树,正式构建时通过rollup-plugin-html实现将HTML作为纯字符串导入,运行完全正常。
问题现象
使用ts-jest编写Jest测试时,HTML文件导入行报错,提示you must enable jsx with babel, ...,但这些导入的并非JSX文件。我需要在测试中像正式构建那样,将HTML作为真实文本值导入,而非使用默认模拟值。
已尝试的解决方案
- 使用
jest-transform-stub、jest-raw-loader作为transform和moduleNameMapper:transform无效果,设置moduleNameMapper虽能跳过导入错误,但测试中HTML值为undefined - 编写自定义转换器,代码如下,但仍未生效:
const fs = require('fs'); module.exports = { process(src, filename) { const content = 'module.exports = ' + JSON.stringify(fs.readFileSync(filename, 'utf8')) + ';'; return content; }, };
当前Jest配置
import path from "path"; import { jestAliasMaps } from "./config/path-aliases-config.js"; import { generalConfigServer } from "./config/general-config-server.js"; export default async () => { return { verbose: true, testEnvironment:'jsdom', transform: { //web component do not compile by babel so they must test with ts '^(?!.*web-components).*\.(js|jsx|tsx|ts)?$': ['babel-jest', { configFile: path.join(generalConfigServer.basePath, 'config', 'babel.config.json') }], '^.*web-components.*\.(js|jsx|tsx|ts)?$': ['ts-jest', { tsconfig: path.join(generalConfigServer.basePath, 'tsconfig-modules.json' ) ,useESM:true}], ".*\\.html$":path.join(generalConfigServer.basePath,'command','test','mocks','html-transform.cjs'), }, moduleNameMapper: { // '.*\\.(css|less|styl|scss|sass)$': path.join(generalConfigServer.basePath, 'command', 'test', 'mocks', 'style-mocks.js'), '.*\\.(css|less|styl|scss|sass)$': ['babel-jest', { configFile: path.join(generalConfigServer.basePath, 'config', 'babel.config.json') }], '.*\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': path.join(generalConfigServer.basePath, 'command', 'test', 'mocks', 'media-mocks.js'), ".*\\.html$": path.join(generalConfigServer.basePath,'command','test','mocks','html-transform.cjs'), // ".*\\.(htm|html)$": 'identity-obj-proxy', ...jestAliasMaps, }, setupFiles: ['raf/polyfill'], globals: { NODE_ENV: "test" }, injectGlobals: false }; };
内容的提问来源于stack exchange,提问作者javad bat
相关产品推荐
相关产品推荐

