Custom fixtures

Crafting custom, domain-specific utilities is a great way to elevate your test setup and turn your tests into a composition of declarative steps and assertions that follow them. As always, there are multiple ways to approach test utilities. You can just import them when you need them or you can use fixtures instead.
Vitest's concept of a fixture is heavily inspired by Playwright, where you can access both built-in and custom fixtures from the test context:
import { test } from '@playwright/test'

test('...', ({ page, myCustomFixture }) => {})
//             👆    👆
The first argument to the test callback function is referred to as test context.
Vitest already exposes a few built-in utilities in its test context, such as the expect function:
test('...', ({ expect }) => {
	expect(this).toBe(that)
})
But you can push this further. You can extend the default test context and imbue it with custom fixtures specific to the software you're testing. It's time you learned how.

Your task

Our e-commerce application has a neat utility to calculate any given cart's total using a function called getTotalPrice:
export function getTotalPrice(cart: Cart): number {
	return cart.reduce((total, item) => {
		return total + item.price * item.quantity
	}, 0)
}
It expects a cart: Cart object as the argument, which means that in order to test different calculation scenarios you have to create different states of the cart. You certainly can do that manually in each test or you can utilize a custom fixture to help you out.
👨‍💼 In this one, your task is to extend the default test context in Vitest and implement a custom fixture called createMockCart(). You will use @faker-js/faker to help you with generating random values for your mock, such as cart item names and quantity. You will implement your custom fixture so it has a default random state but also supports overriding that state on the individual test basis to model the scenarios you need.
🐨 Start by installing @faker-js/faker as a dependency:
npm install @faker-js/faker --save-dev
🐨 Next, proceed to file ane follow the instructions to implement a custom fixture.
🐨 Once the fixture is ready, import the custom test function you've created in the test file and complete it. By the end, run npm test to verify that your tests are passing.
Good luck!

Please set the playground first

Loading "Custom fixtures"
Loading "Custom fixtures"