【问题标题】:Sinon withArgs Custom MatcherSinon withArgs 自定义匹配器
【发布时间】:2021-06-09 23:13:05
【问题描述】:

我正在尝试使用自定义匹配器来存根一个函数,该函数在我的 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')
})

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

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

在使用chai-http 进行测试时,是否有一种特殊的方法来存根函数,例如fs.readFileSync?我之前能够成功存根 fs.writeFileSync(),但存根 fs.readFileSync() 时遇到问题。

【问题讨论】:

  • 我认为您需要披露更多代码。很难推理。但是没有特殊的语法/方法来存根这些函数,没有。附:默认的sinon对象一个沙盒,所以你可以在sinon.stub()之后调用sinon.restore()

标签: javascript node.js mocha.js sinon chai-http


【解决方案1】:

我可以通过这个测试示例确认 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多