Sinon withArgs 自定义匹配器

问题描述

我正在尝试使用自定义匹配器来存根一个函数,该函数在我的 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 时,在使用 fs.readFileSync() 测试我的休息端点时,我总是收到 400 状态代码。我的存根实现似乎阻止了 rest 端点甚至在 rest 端点内执行函数。当匹配器函数触发时,我可以(通过日志记录)验证它是否通过我的 node_modules 以查看是否有任何 fs.readFileSync() 函数需要返回替代值。

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

在使用 fs.readFileSync 进行测试时,是否有一种特殊的方法可以存根 chai-http 之类的函数?我之前能够成功存根 fs.writeFileSync(),但我无法存根 fs.readFileSync()

解决方法

我可以通过这个测试示例确认 stub.withArgs() 和 sinon matchers 工作。

// 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)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...