Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stub a function with arguments

I'm trying to stub a method which takes arguments.

I normally use my object like so:

const res = await Obj.find('admin', 'type');

This works. It either returns null or an object.

I normally stub this like so:

sandbox.stub(Obj.prototype, 'find', function () {
  return Promise.resolve({ id: 123 });
});

I'd like to stub it so that the arguments are taken into account. I've been reading http://sinonjs.org/docs/#stubs and it's supposed to look like the following:

const stub = sinon.stub(Obj.prototype.find);
stub.withArgs('admin', 'type')
  .returns(Promise.resolve({ id: 123 }));
stub.withArgs('user', 'type').returns(null);

I however get the error:

 TypeError: Attempted to wrap undefined property undefined as function
  at Object.wrapMethod (node_modules/sinon/lib/sinon/util/core.js:114:29)
  at Object.stub (node_modules/sinon/lib/sinon/stub.js:67:26)

console.log(Obj.prototype.find); results in:

[Function: find]
like image 608
basickarl Avatar asked Aug 29 '26 21:08

basickarl


1 Answers

Arghhh, I was nearly correct. Below is working code:

const stub = sinon.stub(Obj.prototype, 'find');
stub.withArgs('admin', 'type')
  .returns(Promise.resolve(new User({ id: 123 })));
stub.withArgs('user', 'type').returns(null);
like image 166
basickarl Avatar answered Aug 31 '26 14:08

basickarl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!