模拟fs.readdir进行测试

Jan*_*aer 6 mocking stub node.js sinon

我正在尝试为我的测试模拟函数fs.readdir.

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

stub(fs, 'readdir').yieldsTo('callback', { error: null, files: ['index.md', 'page1.md', 'page2.md'] });
Run Code Online (Sandbox Code Playgroud)

我的第二次尝试是使用自替换函数来模拟函数.但它也行不通.

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;
});
Run Code Online (Sandbox Code Playgroud)

任何人都可以告诉我为什么两者都不起作用?谢谢!


更新 - 这也不起作用:

  sandbox.stub(fs, 'readdir', function (path, callback) {
    callback(null, ['index.md', 'page1.md', 'page2.md']);
  });
Run Code Online (Sandbox Code Playgroud)

UPDATE2:

当我试图在我的测试中直接调用此函数时,我最后一次尝试模拟readdir函数正在工作.但是当我在另一个模块中调用mocked函数时.

Jan*_*aer 6

我找到了问题的原因.我在我的测试类中创建了mock,试图用supertest测试我的rest api .问题是测试是在我的网络服务器运行的过程中在另一个进程中执行的.我在我的测试类中创建了express-app,测试现在是绿色的.

这是测试

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

    beforeEach(function (done) {
      sandbox = sinon.sandbox.create();

      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();
        });
    });
});
Run Code Online (Sandbox Code Playgroud)