用于测试的模拟fs.readder



我正试图为我的测试模拟函数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测试我的rest api。问题是,测试是在另一个进程中执行的,该进程是我的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();
        });
    });
});

最新更新