unjs / consola

🐨 Elegant Console Logger for Node.js and Browser
Other
6k stars 175 forks source link

`mockTypes` does not forward to `withTag` #183

Closed antfu closed 1 year ago

antfu commented 1 year ago

Describe the feature

Context:

In the tailwind module, we use useLogger to create a scoped logger.

const logger = useLogger('nuxt:tailwindcss')

When we want to test it with mockTypes it doesn't work. Because useLogger uses withTag, which creates a new instance of consola and does not forward the mockTypes. And since withTag creates a new instance inside the module, there is no way for a test runner to mock it without exporting the instance.

I have two solutions in mind:

Solution 1

Expose a queryByTag global function to get the logger instance with the tag, or even make each tag singleton

Solution 2

A global mockTypes function that you can pass a tag to, and for each consola instance it will search for the registered mock function to run. This way we could test only the scoped logger.

Additional information

pi0 commented 1 year ago

6864928262e0d6411fcec0f56af97cf667c157a0 should solve it. (notice that logFn - the factory -) is inherited from parent instance.

Regarding global instance usage, consola < v3 was always using a global and shared instance to reuse but it could make backward compatibility issues if we started to do this. maybe later and specially for this kind of mocks to avoid re-running mock-fn, we add it back.

antfu commented 1 year ago

Been able to inherit is good, but do you think it would be better to also able to have the tag passed to the mock function so we can test based on different scope/tag?

pi0 commented 1 year ago

Yes that would be also nice! (feel free to make a PR for fix)