1

我似乎无法从 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.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": {}
  ...
}

任何帮助深表感谢!

4

1 回答 1

5

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

});
于 2017-07-18T21:43:00.187 回答