模拟文件系统的readdir以进行测试

6
我想要模拟测试中的函数 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函数成功了,当我在测试中直接调用这个函数时。但是当我在另一个模块中调用模拟的函数时却不起作用。

1个回答

6
我找到了问题的原因。在我的测试类中,我创建了一个mock并尝试使用supertest测试我的rest api。问题在于测试是在另一个进程中执行的,而不是在我的web服务器运行的进程中执行的。我在测试类中创建了express-app,现在测试已经通过了。
这是一个测试。
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();
        });
    });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接