Skip to content

Instantly share code, notes, and snippets.

@trikitrok
Created March 21, 2025 00:13
Show Gist options
  • Save trikitrok/2909137a57a2d0bb2c2a906bfe657e87 to your computer and use it in GitHub Desktop.
Save trikitrok/2909137a57a2d0bb2c2a906bfe657e87 to your computer and use it in GitHub Desktop.
class Account {
private balance: number;
private readonly logger: AcmeLogger;
constructor(balance: number) {
this.balance = balance;
this.logger = new AcmeLogger();
}
public withdraw(value: number): void {
this.balance += value;
this.logWithdraw(value);
}
private logWithdraw(value: number): void {
// side effect that impedes unit testing
this.logger.logTransaction(new Date(), -value);
}
}
class AcmeLogger {
public logTransaction(date: Date, value: number): void {
// Logger implementation
}
}
//////////////////////////////////////////////
class AcmeLogger {
public logTransaction(date: Date, value: number): void {
// Logger implementation
}
}
class Account {
private balance: number;
private readonly logger: AcmeLogger;
constructor(balance: number) {
this.balance = balance;
this.logger = new AcmeLogger();
}
public withdraw(value: number): void {
this.balance += value;
this.logWithdraw(value);
}
//!! made it protected for testing
protected logWithdraw(value: number): void {
this.logger.logTransaction(new Date(), -value);
}
}
// And in some test class you will use something like:
class ForTestingAccount extends Account {
public loggedWithdrawals: number[];
constructor(balance: number) {
super(balance);
this.loggedWithdrawals = [];
}
// overridden to sense or separate (sensing in this case)
protected override logWithdraw(value: number): void { // keyword override supported for TypeScript 4.3 or later
// do whatever we want, in this case we are spying
this.loggedWithdrawals.push(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment