Curyous
Curyous

Reputation: 8866

How do you use a Typescript Unit Test to test Typescript in Visual Studio?

I'm trying to write a unit test in Typescript to test a Typescript class, but when the test is run, it doesn't know anything about the class.

I'm using Typescript (1.4) with Node Tools for Visual Studio (2013) and the test helpfully appears in Test Explorer. When run it fails with "Reference Error: ClassC not defined."

The class I'm testing:

class ClassC {
    functionF() {
        return 42;
    }
}

Generated Javascript:

var ClassC = (function () {
    function ClassC() {
    }
    ClassC.prototype.functionF = function () {
        return 42;
    };
    return ClassC;
})();
//# sourceMappingURL=ClassC.js.map

The test (created from template Add -> new Item... -> TypeScript UnitTest file):

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

import assert = require('assert');

export function classCTest() {
    var foo: ClassC = new ClassC();

    var result: number = foo.functionF();
    assert.equal(result, 42);
}

Generated Javascript:

var assert = require('assert');
function classCTest() {
    var foo = new ClassC();
    var result = foo.functionF();
    assert.equal(result, 42);
}
exports.classCTest = classCTest;
//# sourceMappingURL=ClassC_tests.js.map

When looking at the generated Javascript for the test it becomes obvious why the error occurs. It does not contain the necessary definition for ClassC. I thought including the reference path would help, but it obviously didn't.

How do I get the unit test to know about the class?

Upvotes: 1

Views: 1407

Answers (1)

basarat
basarat

Reputation: 276057

I thought including the reference path would help, but it obviously didn't.

export class ClassC and then use an import statement instead of a reference comment. Also compile with the compiler flag --module commonjs.

More : https://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1 and http://basarat.gitbooks.io/typescript/content/docs/project/external-modules.html

Upvotes: 1

Related Questions