Mock implementation
Loading "Mock Implementation"
Run locally for transcripts
In this one, we have an
OrderController
class responsible for handling orders in our eshop. It has a .createOrder()
method that accepts a cart
object and does the following:- Throws an error if any of the cart items are out of stock;
- Otherwise, creates a new order object and returns it.
The
.createOrder()
method relies on another .isItemInStock()
method of the same class to check any given cart item's availability. public createOrder(args: { cart: Cart }): Order {
const itemsOutOfStock = args.cart.filter(
(item) => !this.isItemInStock(item),
)
if (itemsOutOfStock.length > 0) {
const outOfSocketItemIds = itemsOutOfStock.map((item) => item.id)
throw new Error(
`Failed to create an order: found out of stock items (${outOfSocketItemIds.join(
', ',
)})`,
)
}
return {
cart: args.cart,
}
}
The data for the item availability itself comes from the
stock.json
file that π¨βπΌ Peter the Project Manager does a faithful job of updating on a daily basis (think of this JSON file as any source of dataβe.g. a database).import stockJson from './stock.json'
export class OrderController {
// ...
public isItemInStock(item: CartItem): boolean {
const itemInStock = stockJson.items.find((existingItem) => {
return existingItem.id === item.id
})
return itemInStock && itemInStock.quantity >= item.quantity
}
}
That's the responsibility Peter bestowed upon himself.
Your responsibility, however, is to test the
.createOrder()
method on the OrderController
class. There are a couple of ways you can use mocking to help you with that, especially when it comes to modeling different item availability states.π¨βπΌ Write automated tests for both of the expectations toward the
.createOrder()
method by using .mockReturnValue()
and .mockImplementation()
utilities in Vitest to control the behavior of the .isItemInStock()
method. By the end of the exercise, npm test
must pass!