5

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?

4

2 回答 2

4

查看 grunt-ts 参考文件生成:https ://github.com/basarat/grunt-ts#reference-file-generation

您可以做的是有单独的目标,一个用于开发,一个用于测试:

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

现在您只能app/reference.ts从所有文件中引用。当你要运行测试时,为测试而构建,当你要发布/开发时为开发而构建。

另请查看此视频教程:http ://www.youtube.com/watch?v=0-6vT7xgE4Y&hd=1

于 2013-08-23T23:32:42.060 回答
3

您是否考虑过使用测试或间谍框架将实现换成测试实现,而不是加载不同的文件?

在我们的TypeScript项目中,我们使用 jasmine 间谍(https://github.com/pivotal/jasmine/wiki/Spies,http://tobyho.com/2011/12/15/jasmine-spy-cheatsheet/)来伪造依赖关系. 我们照常加载主要源代码,然后使用 createSpyObj 和 spyOn 函数将依赖项替换为测试文件中定义的新 TypeScript。

使用这种方法,您无需对主要源代码或包含路径进行任何修改 - 一切都在测试文件中完成。

于 2013-10-29T11:39:49.057 回答