Mocha 测试不适用于 Typescript 命名空间和三重斜杠导入

Mocha test not working with Typescript namespace and triple slash import

我正在尝试 运行 测试我的 Typescript 文件 validators/validators.ts:

declare function require(arg: string): any;

namespace Validator {
    export function hello() {
        return 'Hello World!';
    }
}

测试文件为src/test.ts:

/// <reference path="../validators/validators.ts" />

const expect = require('chai').expect;

describe('Hello function', () => {
    it('should return hello world', () => {
        const result = Validator.hello();
        expect(result).to.equal('Hello World!');
    });
});

tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2015",
    "module": "system",
    "outFile": "test.js"
  },
  "include": [
    "./*",
  ]
}

运行 tsc 输出 test.js:

var Validator;
(function (Validator) {
    function hello() {
        return 'Hello World!';
    }
    Validator.hello = hello;
})(Validator || (Validator = {}));
/// <reference path="../validators/validators.ts" />
const expect = require('chai').expect;
describe('Hello function', () => {
    it('should return hello world', () => {
        const result = Validator.hello();
        expect(result).to.equal('Hello World!');
    });
});

运行 npm test 失败:

  Hello function
    1) should return hello world


  0 passing (6ms)
  1 failing

  1) Hello function
       should return hello world:
     ReferenceError: Validator is not defined
      at Context.it (src/test.ts:7:24)

package.json 就是:

{
  "scripts": {
    "test": "node_modules/mocha/bin/mocha src/**/test.ts"
  }
}

npm version 输出:

{ npm: '5.5.1',
  ares: '1.10.1-DEV',
  cldr: '31.0.1',
  http_parser: '2.7.0',
  icu: '59.1',
  modules: '57',
  nghttp2: '1.25.0',
  node: '8.9.0',
  openssl: '1.0.2l',
  tz: '2017b',
  unicode: '9.0',
  uv: '1.15.0',
  v8: '6.1.534.46',
  zlib: '1.2.11' }

我在命名空间导入上做错了什么导致了这个?

您需要 运行 mocha 编译文件(大概 src/**/*.test.js)而不是原始 TypeScript 文件(src/**/test.ts)。当 mocha 运行s on test.ts 时,Validator 未在测试中定义,因为它在不同的文件中定义。