我有一个项目,其中有一些脚本可以在其中构建打字稿 Web 组件(here)。 我使用 rollup 和 typescript 来构建我的 Web 组件,我的 Web 组件文件如下所示:
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));
}
}
正如你所看到的,我在单独的文件中编写了我的 wc HTML 并将其导入并放入我的 dom 树中,它们都工作得很好。 但是当我尝试用
ts-jest
开玩笑地编写测试时,它卡在 HTML 文件导入行中并显示 you must enable jsx with babel, ...
但它们不是 jsx,我只想将它们作为纯字符串导入,就像 rollup-plugin-html
包所做的那样我的官方构建过程。
问题是我不想用一些默认值来模拟我的 HTML,我需要导入的 HTML 的真实文本值。
目前我尝试了很多方法,例如使用
jest-transform-stub
、jest-raw-loader
作为变换和 moduleNameMapper
。 Transform 不执行任何操作,设置 moduleNameMapper
将通过导入行错误,但 HTML
在实际测试中的值未定义。
我也尝试像这样编写自定义变压器,但仍然不起作用:
const fs = require('fs');
module.exports = {
process(src, filename) {
const content = 'module.exports = ' + JSON.stringify(fs.readFileSync(filename, 'utf8')) + ';';
return content;
},
};
这是我的笑话配置:
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
};
};
请注意这里,转换器应该返回一个具有
code
属性的对象。
如果你这样写你的变压器:
import path from "path";
import fs from "fs";
function process(sourceText, sourcePath, options) {
return {
code: `module.exports = \`${fs.readFileSync(sourcePath)}\`;`,
};
}
const transformer = {
process,
};
export default transformer;
它应该可以正常加载 HTML 文件内容。