'How to mock a function that is called from the function under test?

I work in Mocha. This is ONE of the cases I need mocks/stubs for, but not the only one. I have a one big serviceHelper file and I'm writing unit tests for it.

I have a few functions, let's say verifyAdmin(), verifyUser() etc.

There's one function that collects them together with a switch statement - if param is 'admin' it calls verifyAdmin, if param is 'user' calls verifyUser etc.

So since I have the first two unit tested, there's no point in re-testing them when trying to test the one function that calls them in the switch statement. I want to mock them and just make sure the proper functions were called.

//serviceHelper.js
async function verifyAdmin(){
   does things and returns isAdmin;
}
async function verifyUser(){
   does things and returns isUser;
}

async function checkSession(session){
switch statement that calls either one of these
}

The issue is - from what I'm finding - there's no way to mock/stub them if they're in the same file.

Or maybe is there and I just can't find it?

Or maybe I should split these in 2 separate files? Is that a good approach? Kind of like 'verificationHelper' module? But then the main verification function (the one with the switch statement) would still be in the service helper, which might be confusing... What's my solution here?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source