Fangliang Xue
Fangliang Xue

Reputation: 364

Better file reference for typescript

I’m fairly new to TypeScript and trying to setup some unit tests for my TypeScript code base. The problem is that my code depends on other's work and all these references are done in the form of hard coded relative paths like “......\somefile.d.ts”. When come to unit test, I want to fake out some of the dependencies but don’t know how to make TypeScript take my Fakes instead of hard coded referenced files.

My question is: is there a way not to hard coding the reference path in source code? Are there things like preprocessor or Macro in TypeScript, or could I use the project system to help resolving dependency, rather than hard coding them in source code?

Upvotes: 5

Views: 1149

Answers (2)

Gerard Condon
Gerard Condon

Reputation: 771

Instead of loading different files have you considered using a test or spy framework to swap out the implementation for a test implementation?

In our TypeScript projects we used jasmine spies (https://github.com/pivotal/jasmine/wiki/Spies, http://tobyho.com/2011/12/15/jasmine-spy-cheatsheet/) to fake out dependencies. We loaded the main source code as normal and then used the createSpyObj, and spyOn functions to replace the dependencies with new TypeScript defined in our test files.

Using this approach you don't need to make any modifications to the main source code or include paths - everything is done in the test files.

Upvotes: 3

basarat
basarat

Reputation: 276303

Check out grunt-ts reference file generation : https://github.com/basarat/grunt-ts#reference-file-generation

What you can do is that have seperate targets, one for dev and one for test :

    dev: {                          
        src: ["app/**/*.ts", "!app/**/*.spec.ts"], // Exclude your spec files 
        reference: "./app/reference.ts", 
        out: 'app/out.js',        
    },
    test: {                          
        src: ["app/**/*.ts"], // Include all files 
        reference: "./app/reference.ts", 
        out: 'app/out.js',        
    },

Now you only reference app/reference.tsfrom all your files. When you want to run tests, build for tests, when you want to release / dev build for dev.

Also check out this video tutorial : http://www.youtube.com/watch?v=0-6vT7xgE4Y&hd=1

Upvotes: 4

Related Questions