sinonjs / sinon

Test spies, stubs and mocks for JavaScript.

Home Page:https://sinonjs.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

It will be nice to have callback to functions inside Object

Tejaswinisana opened this issue · comments

Is your feature request related to a problem? Please describe.
As I work with some dependencies like prompts, I'm unable to test the function inside the object , For example something like this using prompts

const prompts = require('prompts');
 
const response = await prompts({
    type: 'number',
    name: 'value',
    message: 'How old are you?',
    validate: value => value < 18 ? `Nightclub is 18+ only` : true
});

Here if I'm mocking prompts but want to validate the function in validate , Similar to yields() , callArgs()
Describe the solution you'd like
A clear and concise description of what you want to happen.
Similar to yields() , callArgs(), A function I can pass the object and get to call the callback function
Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

**Additional context**
Add any other context or screenshots about the feature request here.

TBH I have a really hard time understanding how the client code is supposed to like. Could you create an example of the API you would like to see? Because you talk about callbacks, but the example you provide has no function that takes a callback as an argument, so it makes no sense as it is. The validate field is not a callback, per se, as it is only being called, but you are not being called back to act upon some other logic with a result. That's probably what the Promise is implicitly doing, I am guessing (not being familiar with the library).

Also this:

want to validate the function in validate

What does that mean? Do you mean to say that you want to validate that the function is being called? If so, I might start to understand what you are asking for ... You want to have the below functionality as a built-in?

const validateCalls = [];
const validateWasCalled = () => !!validateCalls.length;
const argsToCallValidate = [19];

const fakePrompts = sinon.fake({
    type,
    name,
    message,
    validate}) => {
    validateCalls.push(argsToCallValidate);
    const result = validate.apply(null, argsToCallValidate);
    return result? Promise.resolve(result) : Promise.reject(result);
});
myMockingLibrary.replace('prompts', fakePrompts);

That seems a bit exotic to implement, TBH, and I think the API for this might not be all that less complicated than the actual hand coded approach, which at least is easy to understand. So not all that convinced ATM, but do try.

Closing due to lack of feedback.