Node.js 用于测试的Mock fs.readdir

Node.js 用于测试的Mock fs.readdir,node.js,mocking,stub,sinon,Node.js,Mocking,Stub,Sinon,我试图模拟函数fs.readdir进行测试 起初,我尝试使用sinon,因为这是一个非常好的框架,但它没有起作用 stub(fs, 'readdir').yieldsTo('callback', { error: null, files: ['index.md', 'page1.md', 'page2.md'] }); 我的第二次尝试是用一个自替换函数来模拟该函数。但它也不起作用 beforeEach(function () { original = fs.readdir; fs.r

我试图模拟函数fs.readdir进行测试

起初,我尝试使用sinon,因为这是一个非常好的框架,但它没有起作用

stub(fs, 'readdir').yieldsTo('callback', { error: null, files: ['index.md', 'page1.md', 'page2.md'] });
我的第二次尝试是用一个自替换函数来模拟该函数。但它也不起作用

beforeEach(function () {
  original = fs.readdir;

  fs.readdir = function (path, callback) {
    callback(null, ['/content/index.md', '/content/page1.md', '/content/page2.md']);
  };
});

afterEach(function () {
  fs.readdir = original;
});
有人能告诉我为什么两者都不起作用吗?谢谢


更新-这也不起作用:

  sandbox.stub(fs, 'readdir', function (path, callback) {
    callback(null, ['index.md', 'page1.md', 'page2.md']);
  });
更新2:


当我试图在测试中直接调用该函数时,我上次模拟readdir函数的尝试正在工作。但是,当我在另一个模块中调用模拟函数时,情况并非如此。

我已经找到了问题的原因。我已经在我的测试类中创建了mock,试图用supertest测试我的restapi。问题是,测试是在另一个进程中执行的,而我的Web服务器运行的进程也是在另一个进程中执行的。我已经在测试类中创建了express应用程序,现在测试为绿色

这是测试

describe('When user wants to list all existing pages', function () {
    var sandbox;
    var app = express();

    beforeEach(function (done) {
      sandbox = sinon.sandbox.create(); // @deprecated — Since 5.0, use sinon.createSandbox instead

      app.get('/api/pages', pagesRoute);
      done();
    });

    afterEach(function (done) {
      sandbox.restore();
      done();
    });

    it('should return a list of the pages with their titles except the index page', function (done) {
      sandbox.stub(fs, 'readdir', function (path, callback) {
        callback(null, ['index.md', 'page1.md', 'page2.md']);
      });

      request(app).get('/api/pages')
        .expect('Content-Type', "application/json")
        .expect(200)
        .end(function (err, res) {
          if (err) {
            return done(err);
          }

          var pages = res.body;

          should.exists(pages);

          pages.length.should.equal(2);

          done();
        });
    });
});