Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stub method to return nth argument #130

Closed
mbyrne00 opened this issue Jan 24, 2019 · 2 comments
Closed

Stub method to return nth argument #130

mbyrne00 opened this issue Jan 24, 2019 · 2 comments

Comments

@mbyrne00
Copy link

I see in #16 and #19 there was work done to capture arguments which is great for verification, however I'd like to set my mock to always return the nth argument.

This is useful for repository style functions that save an entity and return it again.

In Java mockito this was achieved with thenAnswer()

    // Expect specified method call to return the nth argument
    public static <T> void returnArgument(T methodCall, int argumentIndex) {
        when(methodCall).thenAnswer(invocation -> invocation.getArguments()[argumentIndex]);
    }

The beauty of this in the TS stack is we can also mimick behaviour of returning a new object with additional fields if required, via spread. If there is a simple workaround in the mean time or if I've missed something then I'd love to hear it.

Thanks for the great lib!

@NagRock
Copy link
Owner

NagRock commented Mar 18, 2019

If I understand your question correctly: thenCall should be solution for you.

when(mockedFoo.sampleFunction(anything())).thenCall((...args) => {
  console.log(args[0]);
});

So you can just get all arguments by ...args. Or just give them names.

Please let me know if this satisfies your expectations.

@mbyrne00
Copy link
Author

Hi - that's exactly what I was after. I don't know how I missed that! Many thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants