0

我正在尝试使用自定义匹配器来存根一个函数,该函数在我的 node.js 服务器的测试函数中执行两次。我正在测试的函数fs.readFileSync()使用不同的参数使用了两次。我想我可以使用stub.withArgs()自定义匹配器两次来为两者返回不同的值。

let sandbox = sinon.createSandbox()

before(function(done) {
  let myStub = sandbox.stub(fs, 'readFileSync')
  myStub.withArgs(sinon.match(function (val) { return val.includes('.json')})).returns('some json value')
  myStub.withArgs(sinon.match(function (val) { return val.includes('.py')})).returns('some python value')
})

我面临的问题是,chai-http每当我 stub 用于测试我的休息端点时,我总是得到一个 400 状态代码fs.readFileSync()。我的存根实现似乎阻止了休息端点甚至在休息端点内执行功能。当匹配器函数触发时,我可以验证(通过日志记录)它是否通过我node_modules的来查看是否有任何fs.readFileSync()函数需要返回备用值。

当我运行我的 mocha 测试时,在自定义匹配器中记录了一些日志,我可以验证node_moduleslikeraw-body有他们的fs.readFileSync()函数被存根,但不应该返回替代值,因为匹配器返回false(因为参数不通过我的匹配器)。但是由于某种原因,我的任何fs.readFileSync()函数都没有被存根,甚至没有被执行,因为我的休息端点最终只返回了 400 空响应。

有没有一种特殊的方法来存根函数,比如fs.readFileSync在测试时chai-http?我之前能够成功存根fs.writeFileSync(),但我在存根时遇到了麻烦fs.readFileSync()

4

1 回答 1

0

我可以通过这个测试示例确认带有 sinon匹配器的stub.withArgs()有效。

// File test.js
const sinon = require('sinon');
const fs = require('fs');
const { expect } = require('chai');

describe('readFileSync', () => {
  const sandbox = sinon.createSandbox();

  before(() => {
    const stub = sandbox.stub(fs, 'readFileSync');
    stub.withArgs(sinon.match(function (val) { return val.includes('.json')})).returns('some json value');
    stub.withArgs(sinon.match(function (val) { return val.includes('.py')})).returns('some python value');
  });

  after(() => {
    sandbox.restore();
  });

  it('json file', () => {
    const test = fs.readFileSync('test.spec.json');
    expect(test).to.equal('some json value');
  });

  it('python file', () => {
    const test = fs.readFileSync('test.spec.py');
    expect(test).to.equal('some python value');
  });

  it('other file', () => {
    const test = fs.readFileSync('test.txt');
    expect(test).to.be.an('undefined');
  });

  it('combine together', () => {
    const test = fs.readFileSync('test.txt.py.json');
    // Why detected as python?
    // Because python defined last.
    expect(test).to.equal('some python value');
  });
});

当我使用 mocha 从终端运行它时:

$ npx mocha test.js


  readFileSync
    ✓ json value
    ✓ python value
    ✓ other value
    ✓ combine together


  4 passing (6ms)
于 2021-05-06T04:37:33.087 回答