1
我似乎無法在fj上從NodeJS核心上存取readFileSync。下面的代碼隔離了這個問題。通過運行結果摩卡測試在以下幾點:Proxyquire:不能存根fs.readFileSync
> 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.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文件的依賴關係。我嘗試使用類似版本的依賴關係爲代理:
{
...
"devDependencies": {
"jshint": "^2.9.5",
"jslint": "^0.11.0",
"mocha": "~3.1",
"proxyquire": "^1.8.0",
"sinon": "~1.9"
},
"dependencies": {}
...
}
任何幫助非常感謝!
謝謝,這偉大工程:
試試這個!不過,我有點困惑。 Github上的例子爲fs的方法存根:https://github.com/thlorenz/proxyquire/blob/master/examples/sinon/foo-tests.js。 – Andrew
@Andrew這些例子是舊的(5年的特定文件)。我想在此期間,Node.js內部已經改變。僅僅存儲'fs.readFileSync()'會導致最近Node.js版本中的內容被中斷。 – robertklep