Skip to content

Instantly share code, notes, and snippets.

@trikitrok
Last active March 21, 2025 18:08
Show Gist options
  • Save trikitrok/0043fd35aa3d7be0325a9d652e56041a to your computer and use it in GitHub Desktop.
Save trikitrok/0043fd35aa3d7be0325a9d652e56041a to your computer and use it in GitHub Desktop.
// After applying Subclass & Override Method
class RegisterSale {
// more code...
public addItem(code: Barcode): void {
const newItem = this.getInventory().getItemForBarCode(code);
this.items.push(newItem);
}
// made protected for testing
protected getInventory(): Inventory {
return Inventory.getInstance();
}
// more code...
}
// In some test
describe("RegisterSale", () => {
it('adds an item', () => {
// some more setup code
// We make the ForTestingRegisterSale class return a test double of Inventory
const inventory: jest.Mocked<Inventory> = { getItemForBarCode: jest.fn() };
inventory.getItemForBarCode.mockReturnValue(anItem().withBarcode(code).Build());
const registerSale = new ForTestingRegisterSale(inventory);
// rest of the test...
});
// more tests...
// we subclass & override the getter
class ForTestingRegisterSale extends RegisterSale {
private readonly inventory: Inventory;
constructor(inventory: Inventory) {
super();
this.inventory = inventory;
}
// overridden to separate
protected getInventory(): Inventory {
return this.inventory;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment