Test Simple Logger Functions With Full Code Coverage
Solution 1:
log
isn't covered because it never got called, you stubbed it out with sinon.stub(Logger.prototype, 'log')
.
Your current implementation is difficult to test because Logger
is too coupled to Debug
. Creating instances of dependencies in the constructor is generally not a good idea.
If you invert the dependency, making Logger
's constructor take an IDebugger
instead of the string
name:
importDebug, { IDebugger } from'debug';
exportdefaultclassLogger {
constructor(privatereadonly dbg: IDebugger) {}
publiclog(str: string): void {
this.dbg(str);
}
}
then when you test Logger
, you can easily inject a test double:
it("debugs the input", () => {
const debug = sinon.stub();
const logger = newLogger(debug);
const message = "hello, world!";
logger.log(message);
sinon.assert.calledWithExactly(debug, message);
});
This means you don't need to spy on any part of Logger
itself, allowing you to refactor inside that class more easily. The Logger
class now only depends on the abstract IDebugger
interface, not the concrete Debug
implementation.
Creating a Logger
instance with a Debug
given the specific name can just be a function, or a static method:
exportdefaultclassLogger {
staticwithName(name: string) {
returnnewLogger(Debug(name));
}
/* ... */
}
Post a Comment for "Test Simple Logger Functions With Full Code Coverage"