Sinon: Feature - stub.resolvesArg( )

Created on 18 Jan 2018  路  7Comments  路  Source: sinonjs/sinon

This feature would allow users to easily create stubs that resolve to their first argument.

stub.resolvesArg(index);

Causes the stub to return a promise that resolves to the argument at the provided index.

Most helpful comment

@stifflerus Probably did, but still we do have this implemented now since Sinon 6.1 - see #1846.

All 7 comments

We have had this feature for a year :-)

Is there a way to use stub.resolve() to return a promise of the first argument the stub is called with? I don't see that described in the documentation.

So for example:

let mystub = stub.resolvesArg(0);
mystub(arg1, arg2); //returns Promise.resolve(arg1)

mystub = stub.resolvesArg(1);
mystub(arg1, arg2); //return Promise.resolve(arg2)

I don't think there is a way to do this using stub.resolve(), but if there is it would be helpful to document it

@stifflerus As a workaround, you can do something like this:

// pretend this is the code under test
function subject(fn) {
  return fn("foo");
}

it("should work", async () => {
  const mystub = spy(val => Promise.resolve(val)); // stub.resolvesArg(0);
  const result = await subject(mystub); 

  assert(mystub.calledOnce);
  assert.equal(result, "foo");
})

This works:

const myStub = sinon.stub().callsFake(arg1 => Promise.resolve(arg1));

@snoblenet Thanks for your reply. That is basically the same solution as @MrLeebo, but using a stub instead of a spy. I think perhaps @fatso83 misunderstood my feature request. stub.resolvesArg() would have distinct behavior from stub.resolves() in the same way that stub.returnsArg() has distinct behvaior from stub.returns().

@stifflerus Probably did, but still we do have this implemented now since Sinon 6.1 - see #1846.

Was this page helpful?
0 / 5 - 0 ratings