IliaEremin
IliaEremin

Reputation: 3397

Sinon stub withArgs ignores extra arguments

My production code looks like:

exports.convertWord = number => { /* some logic here */ }
exports.methodUnderTest = () => {
    return exports.convertWord(1);
}

Test code:

const mockConvertToWord = sinon.stub();
mockConvertToWord.withArgs(1).returns('one');
fileUnderTest.convertWord = mockConvertToWord;

const result = fileUnderTest.methodUnderTest();

expect(result).toBeEqual('one');

Test above is green. I expect my test will break if I change prod code to this:

exports.convertWord = number => { /* some logic here */ }
exports.methodUnderTest = () => {
    return exports.convertWord(1, 'another arg');
}

but it's not. Sinon works fine even when I pass extra params which I didn't point in withArgs method. How can I tell sinon to return value only when method has been called with exact number of params?

Upvotes: 2

Views: 1818

Answers (2)

Brian Adams
Brian Adams

Reputation: 45780

stub

One way to do this is to use stub.callsFake(fakeFunction):

mockConvertToWord.callsFake((...args) => args.length === 1 && args[0] === 1 ? 'one' : undefined);

An alternative approach with a stub is to use a sinon.assert to make sure the stub was called with the epected arguments as noted by @deerawan.


mock

Another approach is to use a mock:

const mock = sinon.mock(fileUnderTest);
mock.expects('convertWord').withExactArgs(1).returns("one");

const result = fileUnderTest.methodUnderTest();  

expect(result).toBeEqual('one');
mock.verify();

Upvotes: 2

deerawan
deerawan

Reputation: 8443

Another alternative, perhaps you can try to check the call of convertToWord like

...
expect(result).toBeEqual('one');

// check the function 
sinon.assert.alwaysCalledWithExactly(mockConvertToWord, '1');

Ref:

Hope it helps

Upvotes: 1

Related Questions