I
I
Igor Makhov2021-10-21 14:42:56
JavaScript
Igor Makhov, 2021-10-21 14:42:56

How to write a unit test for a function that calls another function?

Suppose you have a utils.ts file like this (quite exaggerated example) that needs to be tested with Jest:

export function a(param: number): void {
    const data = param * 2;
    b(data);
}

export function b(param: number): void {
    console.log(`This is param: ${param}`);
}

Function b does something with the data and can return something, there will be no problems with testing it. The question is what to do with function a, which can do some transformations, but which calls function b. You need to either somehow wet b, or catch her call. There was an idea to make all functions take all other functions that they call as arguments (something like dependency injection), but then, firstly, it turns out that all functions will accept callbacks, and this is not so easy to read, secondly, the functions that are called the very first will have to accept all the code of the rest of the program in the form of a giant list of callbacks. And another problem is that in this particular case, since a only calls b, you could make a return a value and b be called from outside, but in the general case, a can call many different functions and then this solution will not work. Maybe there is another way to organize all this without creating DI?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question