Umair Sarfraz
Umair Sarfraz

Reputation: 6079

Sinon: Test function return value

I am using Sinon Enzyme for testing. I have a function that takes an array of objects and transform it into a new different array.

getContainersByHostId(data) {
    return _.chain(data)
      .groupBy('hostId')
      .toPairs()
      .map(currentItem => _.zipObject(['hostId', 'containers'], currentItem))
      .value();
  }

Args:

const containers = [{
          id: 'c_01',
          hostId: 'h_01',
          hostIp: '192.168.1.0',
          name: 'Some Container'
        }];

Result:

[{hostId: 'h_01',
containers: [{
hostId: 'h_01',
ip: '192.168.1.0',
id: 'c_01',
name: 'Some Container'
}]}];

This works fine. However, the issue I am facing is in the unit test. So currently I have this.

const containers = [{
          id: 'c_01',
          hostId: 'h_01',
          hostIp: '192.168.1.0',
          name: 'Indigo Container'
        }];

        const wrapper = shallow(<Groups {...props} />);
        const instance = wrapper.instance();
        sandbox.stub(instance, 'getContainersByHostId');
        instance.getContainersByHostId(containers);
        expect(instance.getContainersByHostId.calledWith(containers)).to.equal(true);
      });

How to test if the args that are passed equal to new array?

Update:

I have tried returnValue but it gives me false and I couldn't find any possible solution to check what it's really returning.

Upvotes: 1

Views: 5617

Answers (1)

Alexandr Lazarev
Alexandr Lazarev

Reputation: 12892

First of all, when you are stubbing a function, you cancel all it's behaviour, so if you do not specify some value for this stub to return then it will return undefined. Most probably you've confused it with sinon.spy().

If I understood you correctly all you need can be achieved even more easier. No need in Sinon at all. Something like:

const modified = instance.getContainersByHostId(inputArray);    
expect(modified).to.eql(expectedArray);

Upvotes: 3

Related Questions