在javascript测试框架中任何等同于Mockito的ArgumentCaptor?

时间:2016-01-12 10:31:55

标签: javascript testing

我想捕获传递给stub方法的参数。然后我可以对该参数的属性执行断言。对于Java,它是Mockito的ArgumentCaptor。在javascript测试框架中有没有相同的东西?

1 个答案:

答案 0 :(得分:3)

以下是一个例子:

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提供)来检查是否使用特定参数调用了间谍/存根。您应该咨询the documentation以获取更多选项。

这是一个独立的Mocha测试,用于检查间谍是否使用特定属性设置为特定值的对象进行调用:

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