我似乎无法在NodeJS核心的fs上存根readFileSync。以下代码隔离了该问题。通过Mocha运行测试会产生以下结果:
> mocha tests/test.js
Some description
1) "before all" hook
0 passing (15ms)
1 failing
1) Some description "before all" hook:
TypeError: Cannot read property 'charCodeAt' of undefined
at Object.stripBOM (internal/module.js:48:14)
at Object.require.extensions.(anonymous function) (node_modules/proxyquire/lib/proxyquire.js:276:43)
at Proxyquire._withoutCache (node_modules/proxyquire/lib/proxyquire.js:179:12)
at Proxyquire.load (node_modules/proxyquire/lib/proxyquire.js:136:15)
at Context.<anonymous> (tests/test.js:12:15)
这里有test / test.js
var proxyquire = require('proxyquire'),
sinon = require('sinon'),
fs = require('fs'),
sut;
describe('Some description', function () {
var readFileSyncStub;
before(function () {
readFileSyncStub = sinon.stub(fs, 'readFileSync');
readFileSyncStub.withArgs('someFile.js', { encoding: 'utf8' }).returns('some text');
sut = proxyquire('../sut', { fs: { readFileSync: readFileSyncStub } }); // Exception encountered somewhere in here ...
});
after(function () {
fs.readFileSync.restore(); // This is executed ...
});
it('Some it', function () {
// This never happens ...
});
});
这是sut.js,这是正在测试的模块:
var fs = require('fs'); // The code in this file is never executed ...
module.exports = function () {
return fs.readFileSync('someFile.js', { encoding: 'utf8' });
};
项目的文件夹结构是:
./sut.js
./package.json
./tests/test.js
test.js可以通过从提示符执行mocha tests/test.js
来运行。
我注意到几年前在Github上报道的一个问题看起来很相似,但我无法判断它是同一个问题还是另一个问题。这是链接:
https://github.com/thlorenz/proxyquire/issues/12
如果它有帮助,这些是我的package.json文件中的依赖项。我尝试使用类似版本的proxyquire的依赖项:
{
...
"devDependencies": {
"jshint": "^2.9.5",
"jslint": "^0.11.0",
"mocha": "~3.1",
"proxyquire": "^1.8.0",
"sinon": "~1.9"
},
"dependencies": {}
...
}
非常感谢任何帮助!
答案 0 :(得分:3)
如果您 使用fs.readFileSync()
来替换它,则无需存根proxyquire
(事实上,存根fs.readFileSync()
会导致您的问题,因为它打破了require()
和proxyquire
)。
试试这个:
describe('Some description', function () {
var readFileSyncStub;
before(function() {
readFileSyncStub = sinon.stub()
.withArgs('someFile.js', { encoding: 'utf8' })
.returns('some text');
sut = proxyquire('../sut', { fs : { readFileSync : readFileSyncStub } });
});
it('Some it', function () {
let value = sut();
assert.equal(value, 'some text');
});
});