Testing Cart Mutations in Hydrogen: Best Practices
Introduction
Hydrogen storefronts rely heavily on cart mutations to handle add, update, and remove flows. But these APIs are easy to misuse, leading to bugs like duplicate lines, failed updates, or inconsistent cart states.
This post provides best practices for testing cart mutations in Hydrogen, with examples of unit tests, guardrails, and common pitfalls.
Cart Mutations 101
- Add Lines → cartLinesAdd
- Update Lines → cartLinesUpdate
- Remove Lines → cartLinesRemove
Key distinction:
- lineId = unique cart line identifier.
- variantId = product variant.
👉 Bug source: developers often confuse variantId with lineId.
Example: Removing a Line
Mutation
mutation cartLinesRemove($cartId: ID!, $lineIds: [ID!]!) { cartLinesRemove(cartId: $cartId, lineIds: $lineIds) { cart { id lines(first: 10) { edges { node { id, quantity } } } } } }
Jest Test
test("removes line from cart", async () => { const cart = await createCartWithLine(); const lineId = cart.lines[0].id; const result = await removeLine(cart.id, lineId); expect(result.lines).toHaveLength(0); });
Best Practices for Testing
1. Test Line ID vs Variant ID
- Always assert lineId is used for updates/removes.
- Add unit tests that throw if variantId is passed accidentally.
2. Guard Against Double Mutations
- Ensure cartLinesAdd doesn’t duplicate lines unnecessarily.
- Write tests for “merge on add” vs “new line on add.”
3. Validate Edge Cases
- Remove line that doesn’t exist → should fail gracefully.
- Update quantity to 0 → should behave like cartLinesRemove.
4. Use Mock Data Generators
- Scaffold carts in tests with helper functions:
function mockCartLine(variantId: string, qty = 1) { return { id: `line_${variantId}`, variantId, quantity: qty }; }
5. Integrate with Playwright E2E
- Automate add/update/remove flows in browser.
- Assert UI updates match GraphQL state.
Guardrails for Developers
- ✅ Type-safe mutation wrappers.
- ✅ Unit tests for all cart flows.
- ✅ Playwright integration for end-to-end checks.
- ✅ Error boundaries in UI for failed mutations.
Case Study: Fashion Brand
- Initial Hydrogen build → frequent cart bugs.
- Issues: developers confused variantId vs lineId.
- Fixes: added mutation wrappers + Jest tests for add/update/remove.
- Result: cart bug rate dropped 80%, checkout funnel stabilized.
Conclusion
Cart mutations are the backbone of Hydrogen commerce. Testing them rigorously ensures carts stay consistent, checkout funnels don’t break, and customers trust the experience.
A broken cart = a broken store. Guard it with tests.