我正在尝试为我的测试模拟 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']);
});
UPDATE2:
当我尝试在我的测试中直接调用此函数时,我最后一次尝试模拟 readdir 函数正在运行。但是当我在另一个模块中调用mocked函数时,不是这样。
答案 0 :(得分:6)
我找到了解决问题的原因。我在我的测试类中创建了模拟试图用 supertest 测试我的休息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();
});
});
});