Stubbing a Chain of Methods

919 views
Skip to first unread message

Diwa del Mundo

unread,
May 28, 2015, 3:33:58 AM5/28/15
to sin...@googlegroups.com
Hi,

Is there an easy way for stubbing a chain of methods in sinon? Say I have something like this:

Message.find().populate().exec(function(err, results) {
  if(err) {
    // ...
  }
  else {
    // ...
  }
});

To simulate the success and error scenarios for exec(), I basically need to stub the find() method with something like this:

sinon.stub(Message, 'find', function() {
          return {
            populate: function() {
              return {
                exec: function(errorCb) {
                  errorCb(null, []);
                }
              }
            }
          };
        });

While this works, I'm wondering if Sinon provides a shorter and more concise way for stubbing a chain of methods. I'm looking at similar to stub_chain of RSpec: http://www.relishapp.com/rspec/rspec-mocks/v/3-2/docs/old-syntax/stub-chain

Regards,

Diwa

jacob....@gmail.com

unread,
May 28, 2015, 11:15:02 AM5/28/15
to sin...@googlegroups.com
I typically use sinon.stub().returnsThis() for these types of API methods.

From: Diwa del Mundo
Sent: ‎5/‎28/‎2015 0:34
To: sin...@googlegroups.com
Subject: Stubbing a Chain of Methods

--
You received this message because you are subscribed to the Google Groups "Sinon.JS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sinonjs+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Morgan Roderick

unread,
May 28, 2015, 1:07:50 PM5/28/15
to sin...@googlegroups.com
This is one of the reasons why I try to avoid chaining whenever possible.

It might make things easier at the time of writing, but rarely makes things easier for all the subsequent times where you (or another programmer) has to read the code.

And, it certainly doesn't make things easier, when it comes to separating things out and setting up your tests.

How about separating out the function at the end (which I assume is what you're trying to test) into a static function? Then it should be very easy to test it, just by passing it the arguments you want it to receive.

Diwa del Mundo

unread,
May 31, 2015, 9:35:27 PM5/31/15
to sin...@googlegroups.com

How about separating out the function at the end (which I assume is what you're trying to test) into a static function? Then it should be very easy to test it, just by passing it the arguments you want it to receive.


Yes, that's what I thought too. Chaining definitely makes things easier at first, but may end up hard to maintain.


I typically use sinon.stub().returnsThis() for these types of API methods

Ahh let me try that.

Thanks!
Reply all
Reply to author
Forward
0 new messages