-1

I'm a novice JavaScript developer, and I'm having trouble with unit tests. I am using Jest. I run the tests with Node.js 13.14.0 (I use the older version because I have Windows 7). I had the following problem: I needed to mock a function from the same module where the function I'm testing is located. Simply put, the function calls another function from the same module, and I want to make sure it gets called. After searching on Google, I didn't find a complete solution. I liked the option of using the rewire plugin, but that breaks code coverage. I export functions from the module as follows:

module.exports = {
    functions...
}

Then I import them into the test file using require.

I saw that people who encountered this problem were advised some methods using ES6 modules, but I haven't been able to figure out how to make them work and I don't have a pressing need to use them in my project. So still, is there any full-fledged solution? Maybe I should use a different testing framework? And I don't really understand why this problem exists at all. Is using one function per module a common practice?

Anyway, I'm looking for some simple way, like using rewire:

const otherFuncMock = module.__set__(otherFunc, jest.fn())

module.func() // calls otherFunc()

expect(otherFuncMock).toHaveBeenCalledTimes(1)
  • Use `Sinon` library to create stubs, mocks and spies for JS. It's easy to use and simple; and you will also get lot of examples there... https://sinonjs.org – Rahul Kumar Jul 25 '21 at 04:36
  • But the best solution is simply not to do that - internal calls within the same module are _implementation details_, test the _behaviour_ instead. – jonrsharpe Jul 25 '21 at 07:25
  • To put it another way, functions in the same module are like methods on the same class; I've illustrated why you shouldn't mock that in https://stackoverflow.com/a/66752334/3001761. – jonrsharpe Jul 25 '21 at 10:30

1 Answers1

0

If otherFunc is exported by the module then simply using jest.fn() to mock it should work

const otherFuncMock = just.fn(x => module.otherFunc);
module.func();
expect(otherFuncMock).toHaveBeenCalledTimes(1);

If it isn't exported then I would suggest you don't need this test. The fact it calls another function is an internal implementation concern and you would be better focusing on testing the outcome of the combined function execution.

Mike Hanson
  • 266
  • 1
  • 8