Last active
March 21, 2025 18:08
-
-
Save trikitrok/0043fd35aa3d7be0325a9d652e56041a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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