如何覆盖JS库的variables

我正在为我的CLI项目基于JS库https://github.com/tj/commander.jsunit testing

我试图覆盖几个variables来检查打印帮助信息的function。

我需要创build一个新的命令实例,并设置variables_alias, _name, _descriptionoptions

我有:

 import program from 'commander'; describe('test', function() { before(function() { new program.Command(); program.Command.prototype._alias = 'testAlias'; program.Command.prototype._name = 'testName'; program.Command.prototype._description = 'testDescription'; }); it('first test', function() { console.log(program); }); }); 

而我正在接收一个没有更新variables的“旧”实例。

ES6模块有限制,可以防止您修改它们。 但是,由于目前还没有人支持ES6模块,所以必须使用Babel,而Babel在CommonJS模块系统的顶层实现了ES6模块。 我相信你可以利用这个事实来使用底层的CommonJS来修改导入:

 import commander from 'commander'; commander.default.prototype._alias = 'testAlias'; //or commander.Command._alias = 'testAlias'; 

本质上,你试图做同样的事情(修改一个导入),当他们在testing中“模拟”或“存根”对象的时候,所以同样的想法(以及这个问题)也适用:

如何使用ES6模块模拟unit testing的依赖关系