2 ms·
Singletons are considered 'bad' under general advice because they can make testing hard. As with everything, there is a time and a place, but if you understand
by randomdata 3y ago
Singletons are considered 'bad' under general advice because they can make testing hard.
As with everything, there is a time and a place, but if you understand the tradeoffs to recognize that time and place you won't be soliciting random advice from the internet, and thus won't hear the 'good'.
I get the impression that the JavaScript world largely doesn't care much for testing, though.
- lghh 3y agoWhen using singletons for DB connections in TS, I will generally have a singleton function that returns the resource. So getDatabaseConnection will return a databaseConnection. It’s pretty simple, but it has solved the testing problem for me because within that getResource function I can check if the environment being ran in is a test environment. If so, return a mocked instance. If not, return the real instance. It’s pretty rudimentary, but it’s solved our issues.
- tracker1 3y agoNote, you can also place said singleton as a single export in a module, and test anything using that module with a mock on the loader, which most of the newer testing options for JS support pretty easily.