我试图在我的测试中模拟函数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函数的尝试成功了。但当我在另一个模块中调用模拟函数时就不会了。
发布于 2013-08-05 18:29:30
我已经找到了我的问题的原因。我在我的测试类中创建了模拟,试图用超级测试测试rest。问题是,测试是在另一个进程中执行的,因为我的was服务器正在运行。我已经在我的测试类中创建了快速应用程序,现在测试是绿色的。
这是测试
describe('When user wants to list all existing pages', function () {
var sandbox;
var app = express();
beforeEach(function (done) {
sandbox = sinon.sandbox.create(); // @deprecated — Since 5.0, use sinon.createSandbox instead
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
复制相似问题