代码之家  ›  专栏  ›  技术社区  ›  MakotoE

带有摩卡的TS节点不使用TS\u节点\u项目

  •  0
  • MakotoE  · 技术社区  · 6 年前

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

    项目结构如下所示:

    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节点文档,该命令应通过正确的 tsconfig.json ts节点的路径。

    移动 src/tsconfig.json 若要投影目录并运行相同的命令,则会导致测试成功。我怎样才能通过考试 tsconfig.json ts节点的路径,以便测试正确编译?

    1 回复  |  直到 6 年前
        1
  •  7
  •   MakotoE    6 年前

    哦多么尴尬。。。

    TS_NODE_PROJECT='src/tsconfig.json' mocha --require ts-node/register src/*_test.ts
    
        2
  •  0
  •   Luca Faggianelli    4 年前

    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'
    
    推荐文章