使用 mockery 模拟 fs 模块

Mock fs module using mockery

在我的 nodejs 服务器中,我想模拟 fs 以使用 Mocha 进行测试。 我最终使用了Mockery,但我真的误解了一个概念。

在我的测试中(我也使用 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();
});

但不幸的是,在我的测试过程中,我的模块仍然使用旧的 fs。我明白为什么不起作用。事实上,在我的测试中,我:

现在的问题是:如何告诉我的模块重新要求其依赖项以使用我模拟的 fs 版本?在全球范围内,我如何轻松模拟 fs?

谢谢。

最后,经过测试和测试,我最终没有使用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']) }
);