What testing difficulty might this singleton pattern create?
const LoggerSingleton = (() => {
let instance;
function createLogger() {
const logs = [];
function log(message) {
const timestamp = new Date().toISOString();
logs.push({ message, timestamp });
console.log(`${timestamp}: ${message}`);
}
function getLogs() {
return [...logs];
}
return { log, getLogs };
}
return {
getInstance() {
if (!instance) {
instance = createLogger();
}
return instance;
}
};
})();
This singleton pattern creates testing difficulties due to shared state between tests: 1) Tests that use the logger will affect each other as the logs array persists, 2) Test ordering becomes important as later tests see state changes from earlier tests, 3) It's difficult to isolate tests that depend on the logger, 4) Clearing logs between tests requires explicit cleanup code, 5) Mocking becomes more complex due to the global shared instance, 6) A better approach for testing would include a reset method or dependency injection.