I have a function I am stubbing that gets called with multiple arguments. I want to check just the first argument. The rest are callback function, so I want to
withArgs can be used to match some but not all the arguments.
Specifically, method.get.withArgs(25) will check just the first argument.
This is incorrect:
withArgs()matches all arguments
When withArgs is called it remembers the arguments it was passed here as matchingArguments.
Then when the stub is called it gets all matching fakes here.
matchingFakes is called without a second parameter so it returns all fakes that have matchingArguments that match the arguments passed to the stub starting at index 0 up to the length of matchingArguments. This means that a fake will match when its matchingArguments match the beginning of the arguments passed even if there are additional arguments.
Any matching fakes are then sorted by matchingArguments.length and the one that matches the most arguments is the one that is invoked.
The following test confirms this behavior and passes with sinon version 1.1.0 from 7 years ago, version 1.14.0 from the time this question was asked, and the current version 6.3.5:
import * as sinon from 'sinon';
test('withArgs', () => {
const stub = sinon.stub();
stub.withArgs(25).returns('first arg is 25!');
stub.returns('default response');
expect(stub(25)).toBe('first arg is 25!'); // SUCCESS
expect(stub(25, function () { }, function () { })).toBe('first arg is 25!'); // SUCCESS
expect(stub(10, function () { }, function () { })).toBe('default response'); // SUCCESS
});