Mock fs.readdir for testing

穿精又带淫゛_ 提交于 2019-12-07 05:04:30

问题


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


来源:https://stackoverflow.com/questions/18044737/mock-fs-readdir-for-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!