任何等效于Mockito';javascript测试框架中的ArgumentCaptor?

任何等效于Mockito';javascript测试框架中的ArgumentCaptor?,javascript,testing,Javascript,Testing,我想捕获传递给存根方法的参数。然后我可以对该参数的属性执行断言。对于Java,它是Mockito的。javascript测试框架中是否有类似的东西?下面是一个示例: const assert = require('chai').assert; const expect = require('chai').expect; const sinon = require('sinon'); const obj = { divideByFive(a) { return a / 5; }

我想捕获传递给存根方法的参数。然后我可以对该参数的属性执行断言。对于Java,它是Mockito的。javascript测试框架中是否有类似的东西?

下面是一个示例:

const assert = require('chai').assert;
const expect = require('chai').expect;
const sinon  = require('sinon');

const obj = {
  divideByFive(a) {
    return a / 5;
  },
  testFunc(a, b) {
    return this.divideByFive(a + b) + 23;
  }
};

describe('obj.testFunc()', () => {

  afterEach(() => {
    // Restore to the original implementation
    obj.divideByFive.restore();
  });

  it('should call divideByFive() with the right arguments', () => {
    var spy = sinon.spy(obj, 'divideByFive');
    obj.testFunc(42, 1337);
    assert(spy.calledWith(1379));
  });

  it('should return the value returned by divideByFive(), increased by 23', () => {
    sinon.stub(obj, 'divideByFive').returns(1234);
    expect(obj.testFunc(42, 1337)).to.equal(1257);
  });

});
您可以使用
.calledWith()
(由Sinon提供)检查是否使用特定参数调用了spy/stub。你应该咨询更多的选择

下面是一个独立的Mocha测试,用于检查spy是否使用将特定属性设置为特定值的对象调用:

const assert = require('chai').assert;
const sinon  = require('sinon');
const spy    = sinon.spy();

// Call the spy with an object argument.
spy({ foo : 'bar', xxx : 'yyy' });

// Check the properties.
it('should have called spy with foo:bar', function() {
  assert( spy.calledWithMatch({ foo : 'bar' }) );
});

it('should have called spy with xxx:yyy', function() {
  assert( spy.calledWithMatch({ xxx : 'yyy' }) );
});

it('should have called spy with xxx:zzz (WILL FAIL)', function() {
  assert( spy.calledWithMatch({ xxx : 'zzz' }) );
});

您具体谈论的是哪个javascript测试框架?我使用的是mocha+chai+sinon+Mockry。因为我传递的参数是一个对象而不是单个值,我想检查该对象中的几个属性。使用calledWith是否可以做到这一点?
。calledWith()
仅精确匹配参数,但
。calledWithMatch()
将允许您部分匹配对象(例如,如果您希望确保仅将特定属性设置为特定值,而不考虑对象可能具有的任何其他属性).谢谢,我试过了,效果不错。能否提供一个名为WithMatch的示例?所以我可以把它标记为答案。