我正在尝试使用Jest测试一个Typescript类。因为我需要使用es6的async/await
我需要先将typescript类编译为es6,然后使用babel编译为es5。为了实现这一点,我需要添加到预处理器中。
我当前的预处理器如下所示:
const tsc = require('typescript');
module.exports = {
process: function(src, path) {
if (path.endsWith('.ts') || path.endsWith('.tsx')) {
return tsc.transpile(
src,
{
module: tsc.ModuleKind.CommonJS,
jsx: tsc.JsxEmit.React
},
path,
[]
);
}
return src;
}
};
我是否需要添加target: tsc.ScriptTarget.ES6
?
当我这样做时,我在处理过的代码中出现unexpected identifier =
错误,该错误看起来像我的.ts
类的转换版本。我从中收集的是我的预处理器正在将数据编译为es6,但我的es6没有被转换为es5。
也有任何现成的预处理器可以做到这一点?
答案 0 :(得分:2)
我建议使用https://www.npmjs.com/package/ts-jest这是一个更清洁的解决方案。为您工作的预处理器......
答案 1 :(得分:2)
如果您正在寻找自定义配置,这可能是您的答案:https://stackoverflow.com/a/40070453/4909970
但是,根据我的经验ts-jest运行正常。只要确保你指定
"target": "ES6"
中ts-jest __TS_CONFIG__
的jest设置,或者只是添加当前的打字稿配置。
你package.json
会看到这样的事情:
"jest": {
"scriptPreprocessor": "<rootDir>/node_modules/ts-jest/preprocessor.js",
"globals": {
"__TS_CONFIG__": "tsconfig.json"
}
}
答案 2 :(得分:1)
我目前使用的解决方案是
const tsc = require('typescript');
const babel = require('babel-core');
const jestPreset = require('babel-preset-jest');
const es2015 = require('babel-preset-es2015');
const stage3 = require('babel-preset-stage-3');
module.exports = {
process: function (src, path) {
if (path.endsWith('.ts') || path.endsWith('.tsx')) {
var es6Code = tsc.transpile(
src,
{
target: tsc.ScriptTarget.ES6,
module: tsc.ModuleKind.CommonJS,
jsx: tsc.JsxEmit.React
},
path,
[]
);
return babel.transform(es6Code, {
auxiliaryCommentBefore: ' istanbul ignore next ',
presets: [jestPreset, es2015, stage3],
retainLines: true
}).code;
}
return src;
}
};
所以我在这里做的是我正在使用由typescript编译器生成的转换代码并将其传递给babel,而babel又将我的代码从es6转换为es5。