【问题标题】:TS-Node with Mocha doesn't use TS_NODE_PROJECT带有 Mocha 的 TS-Node 不使用 TS_NODE_PROJECT
【发布时间】:2019-06-27 19:27:28
【问题描述】:

当 ts-node 用于使用 Mocha 进行测试时,我在使用 env 变量 TS_NODE_PROJECT 时遇到问题。

项目结构如下:

src/
  main_test.ts
  tsconfig.json
package.json

在我的测试中,我想使用一个异步函数,它需要"lib": ["es2018"] 作为编译选项。

// src/main_test.ts
describe('', () => {
    it('test', () => {
        (async function() {})()
    });
});

// src/tsconfig.json
{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "lib": ["es2018"]
  },
  "exclude": [
    "../node_modules"
  ]
}

为了运行测试,我使用了这个命令,但是它导致了一个错误:

TS_NODE_PROJECT='src' && mocha --require ts-node/register src/*_test.ts
# TSError: ⨯ Unable to compile TypeScript:
# error TS2468: Cannot find global value 'Promise'.
# src/main_test.ts(3,10): error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor.  Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your `--lib` option.

这意味着src/tsconfig.json 未被使用。根据Overriding `tsconfig.json` for ts-node in mocha 和 ts-node 文档,该命令应该将正确的tsconfig.json 路径传递给 ts-node。

src/tsconfig.json 移动到项目目录并运行相同的命令会导致测试成功。如何将tsconfig.json 路径传递给 ts-node 以便测试正确编译?

【问题讨论】:

    标签: mocha.js ts-node


    【解决方案1】:

    哦。好尴尬……

    TS_NODE_PROJECT='src/tsconfig.json' mocha --require ts-node/register src/*_test.ts
    

    【讨论】:

    • 这非常关键!
    【解决方案2】:

    我发现在不同的文件中移动 mocha 设置非常有用,因此 package.json 保持干净,您可以像这样使用 mocharc 文件:

    module.exports = {
      ignore: [
        './test/helpers/**/*',
        './test/mocha.env.js'
      ],
      require: [
        'test/mocha.env', // init env here
        'ts-node/register'
      ],
      extension: [
        'ts'
      ]
    }
    

    然后使用以下内容创建文件test/mocha.env.js(或随意调用):

    process.env.NODE_ENV = 'test'
    process.env.TS_NODE_PROJECT = 'src/tsconfig.json'
    

    【讨论】:

      猜你喜欢
      • 2019-06-19
      • 1970-01-01
      • 2021-12-27
      • 2022-07-23
      • 2019-09-22
      • 1970-01-01
      • 2021-02-10
      • 2020-09-16
      • 2017-09-28
      相关资源
      最近更新 更多