使用嘲笑模拟fs模块

在我的nodejs服务器上,我想嘲笑我的testing与摩卡。 我最终使用嘲笑,但我真的误解了一个概念。

在我的testing中(我也使用Typescript):

// mock for fs var fsMock = { readdir: (path: string) => { return { err: undefined, files: [] } }, writeFile: (path: string, content: string, encoding: string) => { return { err: undefined } }, readFileSync: (path: string, encoding: string) => { return "lol" } }; Mockery.registerMock('fs', fsMock); beforeEach((done) => { Mockery.enable({ useCleanCache: true, warnOnReplace: false, warnOnUnregistered: false }); } afterEach(() => { Mockery.disable(); }); 

但不幸的是在我的testing中,我的模块仍然使用旧的FS。 我明白为什么不工作。 事实上,在我的testing中,我:

  • 导入我的模块在文件的顶部
  • 当我导入模块时,我的模块将导入它的依赖关系,如fs。
  • 因为在这个时候,嘲讽还没有启用(我们还没有进行testing…),在我的模块导入的fs是原来的
  • 我在testing之前设置了嘲笑
  • 我执行我的testing,失败,因为仍然是原来的FS使用…

现在的问题是:我怎么能告诉我的模块重新要求它的依赖使用我的模拟版本的FS? 而更全球的,我怎么能轻松地嘲笑fs?

谢谢。

最后,经过testing和testing,我最终没有使用mockery ,而是SinonJS 。 它提供了一个非常简单和轻松的方式来模拟fs ,例如:

 import * as Fs from "fs" import * as Sinon from "sinon" // .. // At a place inside a test where the mock is needed Sinon.stub(Fs, "readdir").callsFake( (path: string, callback: Function) => { callback(null, ['toto']) } );