Description
Details
Currently, when adopting the native test runner, it is very hard to understand how to mock standalone functions used in the unit under test. Judging by this SO question, I'm not the only one who can't figure this out 😄
None of the documentation examples on the Test runner demonstrate the mocking of imported functions.
The only way I found to mock functions used in another function is to export all functions of the depended-on function's file, e.g. export default {all, my, functions}
. From a production code standpoint, it's both unnecessary (if I want to only use one function from a file, why should I need to import the whole default and access the function I need as a member?) and in some contexts undesirable (my gut feeling is that it would make treeshaking impossible, but I haven't verified this).
You'll find an example in this repository: https://github.com/GabeAtWork/node-test-runner-cannot-mock-function-minimal-example
The file demonstrates 3 approaches:
- Using default exports and
mock.method
(works, but is not desirable as explained above) - Using single import and
mock.fn
(our go-to way of writing code, but doesn't mock the function, so the actual function gets called) - Using star imports and
mock.method
(would be an ok compromise, but it seems to fail in what looks like a bug)
It may be that there is an alternate way of solving this problem which I haven't found yet, so please do let me know if it exists! Since this feature is so fresh, there's not a lot of content on it yet. Blog posts and videos I found don't actually show functions imported from different files or only show default imports and classes being mocked.
Feature request on the node repo: nodejs/node#51164
Node.js version
20.8.0
Example code
You can find a minimal example in this repository: https://github.com/GabeAtWork/node-test-runner-cannot-mock-function-minimal-example
Operating system
MacOS (but not relevant)
Scope
Documentation / API design
Module and version
Not applicable.