James Haskell
James Haskell

Reputation: 2025

Mocha test not working with Typescript namespace and triple slash import

I'm trying to run tests on my Typescript file validators/validators.ts:

declare function require(arg: string): any;

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

The test file is 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": [
    "./*",
  ]
}

Running tsc outputs 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!');
    });
});

Running npm test FAILS:

  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 is simply:

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

npm version output:

{ 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' }

What am I doing wrong on the namespace import that is causing this?

Upvotes: 1

Views: 1206

Answers (1)

Huy Nguyen
Huy Nguyen

Reputation: 3010

You need to run mocha on the compiled file (presumably src/**/*.test.js) instead of the raw TypeScript files (src/**/test.ts). When mocha runs on test.ts, Validator is not defined in the test because it's defined in a different file.

Upvotes: 2

Related Questions