我可以在TypeScript中使用自定义模块parsing函数(如“proxyquire”)来代替require()吗?
我有一个TypeScript文件config.ts
将与节点运行:
import myDependency = require('my-dependency'); export = { doSomething = () => { ... } }
在其他的TypeScript文件中,我可以import
这个文件的完整types的安全性:
import config = require('./config'); config.doSomething(); config.doSomethingElse(); // compiler error, this method doesn't exist
现在我想unit testing这个脚本。 为了模拟这个脚本所require()
的依赖require()
我使用了proxyquire ,它让我提供脚本在调用require()
时候得到的值。 以下是我的testing可能的样子:
import proxyquire = require('proxyquire'); const config = proxyquire('./config', { 'my-dependency': {} // this mocked object will be provided when config.ts asks for `my-dependency` }); expect(config.doSomething()).to.do.something();
这工作正常,除了我的config
variables是any
types,因为我使用proxyquire()
代替require()
。 TypeScript必须给予require()
函数特殊处理才能执行模块parsing。 有没有办法告诉TypeScript编译器,那么proxyquire()
也应该做模块parsing,类似于require()
?
我可以重写config.ts
作为一个类,或使它使用一个接口。 然后,我将能够通过导入类/接口定义显式地键入我的testing中的variables。 但允许proxyquire()
为我隐式键入事情将是更容易的解决scheme。
有一个解决方法 – 您可以通过导入实际模块并在types转换中使用typeof
来获取config.ts
模块的types:
import proxyquire = require('proxyquire'); import configType = require('./config'); const config = <typeof configType> proxyquire('./config', { 'my-dependency': {} // this mocked object will be provided when config.ts asks for `my-dependency` }); config.doSomething(); // config.noSuchMethod(); // does not compile
这是不理想的,因为你必须在你的testing中导入相同的模块两次 – 真正的只是为了得到它的types和“proxominired”一个在你的testing中实际使用,你必须小心不要混淆他们俩。 但是与为脚本实现另一个模块分辨率变体相比,这非常简单。 而且,当以这种方式使用configType时 – 仅用于input – 它的导入甚至不会出现在生成的javacsript代码中。
- 如何检测用户取消请求
- 如何使用phantomjs或其他浏览器在nodejs中创buildWeb代理?
- 使用像fiddler一样的提取API的代理
- Javascript – 从不同的国家发送singel http请求
- 请求库不正确地通过代理来引导HTTP请求
- 为什么https.Agent在通过node-http-proxy进行代理时会抛出parsing错误?
- 尝试使用协议分析器(Charles)捕获node.js httpstream量,但无法使节点使用代理
- 使用npm包http-proxy在Meteor下设置SSL
- 使Node.js使用http_proxy,https_proxy和no_proxy环境variables