sinonjs / sinonjs/sinon

returnValue of calls is out of order when spying on recursive functions

Open
#1,849 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

pinned
Dominant language
JavaScript
Stars
9.8k
Forks
809
PR merge metrics
No merged PRs in 30d

Description

Describe the bug

The return value, as given by spy.getCall(n).returnValue, is in the wrong order when spying on a recursive function. The return values are in the order that calls returned, instead of the order of the calls themselves. For example, the returnValue of the first call is the value returned by the last call, instead of the value returned by the first call.

Note that this bug occurs with both sinon.spy and sinon.fake.

To Reproduce

recurse.js

function foo(num) {
    if (num < 2) {
        foo(num + 1);
    }

    return num;
}

recurse.test.js

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

const recurse = rewire('../recurse');


describe('foo', function () {
    it('should recursively add 1 but return original number', function () {
        recurse.__with__({
            foo: sinon.fake(recurse.__get__('foo'))
        })(function () {
            recurse.__get__('foo')(0);

            expect(recurse.__get__('foo').getCall(0).returnValue).to.equal(0);
            expect(recurse.__get__('foo').getCall(1).returnValue).to.equal(1);
            expect(recurse.__get__('foo').getCall(2).returnValue).to.equal(2);
        });
    });
});

Expected behavior

spy.getCall(n).returnValue should be the return value of the nth call to spy.

Context:

  • Library version: 6.0.1
  • Environment: Windows
  • Other libraries you are using: mocha, chai, rewire

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the recursive reproduction in recurse.test.js with the sinon.fake wrapper around recurse.js, then trace how calls are recorded for sinon.spy and sinon.fake. Confirm the failure with getCall(n).returnValue and ensure the return value for each call matches that call's invocation order, including nested recursive calls.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
testing-qa
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.