最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Stub a function with arguments - Stack Overflow

programmeradmin5浏览0评论

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 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]

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]
Share Improve this question asked Feb 20, 2017 at 9:41 basickarlbasickarl 40.5k69 gold badges237 silver badges354 bronze badges 1
  • What is at line 67, column 26 of stub.js? – rasmeister Commented Feb 20, 2017 at 9:49
Add a comment  | 

1 Answer 1

Reset to default 16

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);
发布评论

评论列表(0)

  1. 暂无评论