Search code examples
node.jstypescriptmocha.jsphaser-frameworktsd

How to resolve Typescript external dependencies with mocha and node


I've got the following files;

MyClass.ts

/// <reference path="node_modules/phaser/typescript/phaser.d.ts" />
export class MyClass {
    d: Phaser.Sprite;
    constructor() {
        this.d = new Phaser.Sprite(new Phaser.Game, 10, 10);
    }
    win() : boolean {
        return true;
    }
}

test.ts

/// <reference path="../typings/mocha/mocha.d.ts" />
import MyModule = require('../MyClass'); 

describe('MyClass', () => {   
    var subject : MyModule.MyClass;

    beforeEach(function () {
        subject = new MyModule.MyClass();
    });

    describe('#win', () => {
        it('should pass', () => {
            var result : boolean = subject.win();
            if (result !== true) {
                throw new Error('Expected true but was ' + result);
            }
        });
    });
});

I've used tsd to pull in mocha.d.ts and I'm using ts-node to execute typescript in node so I execute mocha as follows;

mocha --compilers ts:ts-node/register

Compilation is successful, however the tests then fail at runtime because Phaser is not defined;

MyClass
    #win
      1) "before each" hook for "should pass"


  0 passing (47ms)
  1 failing

  1) MyClass "before each" hook for "should pass":
     ReferenceError: Phaser is not defined
      at new MyClass (c:\Users\stafford\Documents\git\ts-node-test\MyClass.ts:5:22)
      at Context.<anonymous> (c:\Users\stafford\Documents\git\ts-node-test\test\test.ts:8:19)
      at callFn (C:\Users\stafford\AppData\Roaming\npm\node_modules\mocha\lib\runnable.js:286:21)
      at Hook.Runnable.run (C:\Users\stafford\AppData\Roaming\npm\node_modules\mocha\lib\runnable.js:279:7)
      at next (C:\Users\stafford\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:297:10)
      at Immediate._onImmediate (C:\Users\stafford\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:319:5)

I thought I would then have to do something like this or similar;

import Phaser = require('phaser');

But this then breaks compilation with the error for phaser.d.ts;

phaser.d.ts is not a module.

How can I get such a test to execute via command-line?

repro


Solution

  • import Phaser = require('phaser');

    You should create a vendor.d.ts with the following

    declare module 'phaser' {
        export = Phaser;
    }
    

    This will create a type safe module phaser for you. Don't forget to also include phaser.d.ts : https://github.com/photonstorm/phaser/blob/v2.4.4/typescript/phaser.d.ts

    More

    https://basarat.gitbooks.io/typescript/content/docs/project/modules.html