Typescript/ES6 的 Jest 预处理器

Nah*_*nde 4 typescript ecmascript-6 jestjs

我正在尝试使用 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;
    }
};
Run Code Online (Sandbox Code Playgroud)

我需要添加target: tsc.ScriptTarget.ES6吗?当我这样做时,我unexpected identifier =在处理的代码中得到一个错误,它看起来像我的.ts类的转译版本。我从中收集到的是,我的预处理器正在将数据编译为 es6,但我的 es6 没有被转换为 es5。还有任何现成的预处理器可以做到这一点吗?

pav*_*oko 5

如果您正在寻找自定义配置,这可能是您的答案:https : //stackoverflow.com/a/40070453/4909970

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

package.json会看起来像这样:

"jest": {
    "scriptPreprocessor": "<rootDir>/node_modules/ts-jest/preprocessor.js",
    "globals": {
        "__TS_CONFIG__": "tsconfig.json"
    }
}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

2723 次

最近记录:

8 年,7 月 前