【问题标题】:Mocha test not working with Typescript namespace and triple slash importMocha 测试不适用于 Typescript 命名空间和三斜杠导入
【发布时间】:2018-03-22 19:37:08
【问题描述】:

我正在尝试对我的 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' }

我在导致这种情况的命名空间导入上做错了什么?

【问题讨论】:

  • npm run test 解析的 shell 命令是什么?
  • 在上面添加了package.json(它在“src”和“validators”的父目录中)......它只是“mocha”。仅供参考,我在运行“npm test”之前在“src”中手动运行“tsc”。

标签: typescript mocha.js


【解决方案1】:

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

【讨论】:

  • 是的。谢谢。我犯了一个愚蠢的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-18
  • 1970-01-01
  • 1970-01-01
  • 2018-01-05
  • 2015-09-20
  • 1970-01-01
  • 2013-01-22
相关资源
最近更新 更多