overriding module.exports = function
Closed this issue · 2 comments
Hi, i face myself with the same problem as issue #120 & #123 , but cannot find a way to do it working without changing my module.exports = myFunction
to module.exports = { myFunction}
Here what I have been doing:
fileToTest.js:
const functionToOverride = require('path/to/function')
module.exports = () => {
/* some code*/
const result = functionToOverride(....)
/* some code again.....*/
}
functionToOverride
module.exports = () => {/*some code*/}
testFile.js (assuming this file is located in test directory, which is as the same level as fileToTest.js)
const proxyquire = require('proxyquire');
const myMock = () => {/* some code*/}
const deviceHandler = proxyquire('../fileToTest', { functionToOverride: myMock })
/* proceed to test description*/
When executing the test, the mock is never called and it result in the real function being called.
Am I missing something or doing something wrong?
Thanks in advance for any help !
Proxyquire doesn't override references in your code, it overrides modules. Per your example:
- const deviceHandler = proxyquire('../fileToTest', { functionToOverride: myMock })
+ const deviceHandler = proxyquire('../fileToTest', { 'path/to/function': myMock })
The idea here is that modules are somewhat stable and represent meaningful interfaces between your code. Local variable naming is a purely internal concern and it's unexpected that renaming a variable should break your tests.
Thanks @bendrucker for your response !
Indeed I misunderstood the path/to/function
in the second arguments.