我可以在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代码中。
- 适用于使用代理的客户端的socket.io flash(和其他)回退的正确设置
- 如何通过Nginx反向代理获取POST请求到Node / Express.js
- npm install – >隧道套接字无法build立
- 在可以处理多个安全域的NodeJS中创build一个反向代理
- Nodejs请求代理stream(mjpeg)连接永远不会结束
- proxyquire with require.exports = ClassConstructor
- http-proxy-middleware – 访问静态文件
- 我应该在收到304后closures代理连接吗?
- 如何检查node-http-proxy中的Rails会话?