Typescript/ES6 的 Jest 预处理器

Jest preprocessor for Typescript/ES6

我正在尝试使用 Jest 测试 A Typescript Class。因为我需要使用 es6 的 async/await 我需要先将打字稿 class 编译为 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 class 的转译版本。我从中收集到的是我的预处理器正在将数据编译为 es6 但我的 es6 没有被转译为 es5。 还有没有现成的预处理器可以做到这一点?

我建议使用 https://www.npmjs.com/package/ts-jest,这是一种更简洁的解决方案。为您完成工作的预处理器...

如果您正在寻找自定义配置,这可能是您的答案:

但是,根据我的经验,ts-jest 工作正常。只要确保你指定 在 __TS_CONFIG__ 中为 ts-jest "target": "ES6" 设置开玩笑,或者只添加您当前的打字稿配置。

package.json 会看起来像这样:

"jest": {
    "scriptPreprocessor": "<rootDir>/node_modules/ts-jest/preprocessor.js",
    "globals": {
        "__TS_CONFIG__": "tsconfig.json"
    }
}

我目前使用的这个问题的解决方案是

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,后者又将我的代码从 es6 转换为 es5。