模拟fs.readdir进行testing

我试图嘲笑函数fs.readdir为我的testing。

起初我试过使用sinon,因为这是一个非常好的框架,但是没有奏效。

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

我的第二个尝试是用自我replace函数来模拟函数。 但它也不起作用。

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

UPDATE2:

我最后一次尝试模拟readdir函数正在工作,当我试图直接在我的testing中调用这个函数。 但是当我在另一个模块中调用模拟函数时不行。

我find了我的问题的原因。 我在testing类中创build了模拟,试图用supertesttesting我的restAPI。 问题是testing是在另一个进程中执行的,因为我的web服务器运行的过程。 我在我的testing课中创build了快速应用程序,testing现在是绿色的。

这是testing

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