Carlos Valencia
Carlos Valencia

Reputation: 6963

Jest - Mock function that is not being exported

I have a file that exports one function that relies on a private one:

function __a(filePath, someFunction){
  // do some file request
  someFunction(filePath)
}

function b(filePath){
  __a(filePath, require)
}

module.exports = {
  b: b
}

And I'd like to test that the private function __a toHaveBeenCalledWith some parameters so __a does not actually try and fetch some file I can not assure exists.

I understand the concept that when I'm importing b I am getting a reference to the function and __a just lives within the scope of it, and I can't have access to it so using stuff like:

import appResources from './index';
// ... test
jest.spyOn(applicationResources, '__a').mockImplementationOnce(myParams);

How can I avoid __a excecution here and make sure it's been called?

Upvotes: 1

Views: 4773

Answers (1)

Estus Flask
Estus Flask

Reputation: 222369

It's impossible to mock or spy on existing function that isn't used as a method.

__a and b should either reside in different modules, or a should be used as a method within same module. For CommonJS modules there's existing exports object that can be used:

exports.__a = function __a(filePath, someFunction){
  // do some file request
  someFunction(filePath)
}

exports.b = function b(filePath){
  exports.__a(filePath, require)
}

Notice that module.exports isn't replaced, otherwise it won't be possible to refer it as exports.

Upvotes: 3

Related Questions