Skip to content

Instantly share code, notes, and snippets.

@trikitrok
Created March 21, 2025 18:41
Show Gist options
  • Save trikitrok/663e9d97ab18690bde0e362981d86d39 to your computer and use it in GitHub Desktop.
Save trikitrok/663e9d97ab18690bde0e362981d86d39 to your computer and use it in GitHub Desktop.
Alternative using Parameterize Constructor
// Alternative using Parameterize Constructor
export class User {
private readonly id: number;
private readonly bankingServices: BankingServices;
//!! We used Parameterize Constructor to inject a BankingServices instance to User
constructor(id: number, bankingServices: BankingServices) {
this.id = id;
this.bankingServices = bankingServices;
}
// more code...
public updateBalance(amount: Money): void {
this.bankingServices.updateBalance(this.id, amount);
}
// more code...
}
//!! In some test now we can use a test double of BankingServices to sense or separate
describe("User", () => {
it('updates balance', () => {
const bankingServices: jest.Mocked<BankingServices> = { updateBalance: jest.fn() };
const userId = 1;
const user = new User(userId, bankingServices);
const amount = new Money(200);
user.updateBalance(amount);
expect(bankingServices.updateBalance).toHaveBeenCalledWith(userId, amount); // in this case sensing
});
// more tests...
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment