Mock fs.readdir for testing

2019-04-28 10:01发布

问题:

I'm trying to mock the function fs.readdir for my tests.

At first I've tried to use sinon because this is a very good framework for this, but is hasn't worked.

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

My second attempt was to mock the function with a self-replaced function. But it also doesn't works.

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;
});

Can anybody tell me why both doesn't works? Thanks!


Update - This also doesn't works:

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

Update2:

My last attempt to mock the readdir function is working, when I'm trying to call this function directly in my test. But not when I'm calling the mocked function in another module.

回答1:

I've found the reason for my problem. I've created the mock in my test class tried to test my rest api with supertest. The problem was that the test was executed in another process as the process in that my webserver runs. I've created the express-app in my test class and the test is now green.

this is test

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();
        });
    });
});