我有一个国家预防机制项目:
{
"scripts": {
"test": "jest --config=jest.config.js"
},
"devDependencies": {
"@types/pegjs": "0.10.3",
"@types/jest": "29.1.1",
"ts-loader": "9.3.1",
"raw-loader": "4.0.2",
"typescript": "4.8.3",
"webpack": "5.74.0",
"webpack-cli": "4.10.0",
"jest": "29.1.2",
"ts-jest": "29.0.3"
},
"dependencies": {
"pegjs": "0.10.0"
}
}正如您所看到的,这个项目:
结构:
myproj
|-src/
|-grammar.pegjs
|-index.ts
|-index.test.ts
|-package.json
|-jest.config.js
|-transformer.js运行测试
Jest将把.ts文件转换成Javascript。正如在文档中所解释的,我们需要处理使用Webpack导入静态资产的案例。在本例中,index.ts具有以下内容:
import pegjsgrammar from grammar这需要处理。我正在为那个transformer.js创建一个转换器
const fs = require("fs");
module.exports = {
process(sourceText, sourcePath, options) {
const fileContents = fs.readFileSync(sourcePath, { encoding: "utf8" }).toString();
const json = JSON.stringify(fileContents).replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
return {
code: `module.exports = ${json};`,
};
},
};在jest.config.js内部
module.exports = {
preset: "ts-jest",
transform: {
"\\.tsx?$": "ts-jest",
"\\.jsx?$": "babel-jest",
"\\.pegjs$": "<rootDir>/pegjs_jest_transformer.js"
},
moduleFileExtensions: ["ts", "js", "pegjs"],
};错误
在运行我的测试时,我会得到错误,因为pegjsgrammar在index.ts中的值是undefined。
发布于 2022-10-15 13:13:52
因此,问题在于保证不同模块之间的互操作性。为此,修改tsconfig.json以包括以下选项:
{
"compilerOptions": {
...
"esModuleInterop": true
}
}一切都很好。
https://stackoverflow.com/questions/74075002
复制相似问题