Adding tests before refactoring
Because we don’t want to make any observable behavior changes during refactoring, we need to inspect the code to make sure we have enough tests to cover the current behavior. It’s easy to mess up without the right tests in place, and that’s not only risky but also less efficient, as we need to check the changed code manually and repeatedly.
Let’s say we have some TypeScript code from an online shopping application – the code works fine, but there aren’t any tests associated with it. To improve the code so that it’s easier to understand and extend, we need to refactor it:
interface Item { id: string; price: number; quantity: number; } class ShoppingCart { cartItems: Item[] = []; addItemToCart(id: string, price: number, quantity: number) { this.cartItems.push({ id, price, quantity }); } calculateTotal...