【问题标题】:Jest preprocessor for Typescript/ES6Typescript/ES6 的 Jest 预处理器
【发布时间】:2016-11-20 23:16:51
【问题描述】:

我正在尝试使用 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。 还有任何现成的预处理器可以做到这一点吗?

【问题讨论】:

    标签: typescript ecmascript-6 jestjs


    【解决方案1】:

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

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

    package.json 看起来像这样:

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

    【讨论】:

    • 如果你想使用Webstorm的集成,你必须在package.json中使用这个"globals"
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      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。

      【讨论】:

        猜你喜欢
        • 2018-12-02
        • 2015-07-23
        • 2017-07-02
        • 2017-11-12
        • 2017-06-24
        • 2019-06-10
        • 2017-02-25
        • 1970-01-01
        • 2018-09-07
        相关资源
        最近更新 更多