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)