Mock implementation

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:
  1. Throws an error if any of the cart items are out of stock;
  2. 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!

Please set the playground first

Loading "Mock implementation"
Loading "Mock implementation"

Access Denied

You must login or register for the workshop to view the diff.

Check out this video to see how the diff tab works.