Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
test: Add tests for checkout, addresses, orders, credit-cards, gift-cards, and auth-helpers
Damian Legawiecc538ee488c2f
diff --git a/packages/next/tests/actions/addresses.test.ts b/packages/next/tests/actions/addresses.test.tsnew file mode 100644index 0000000000..7fb05694d7--- /dev/null+++ b/packages/next/tests/actions/addresses.test.ts@@ -0,0 +1,142 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { mockCookieStore } from '../setup';+import { initSpreeNext, resetClient } from '../../src/config';++const mockClient = {+ customer: {+ addresses: {+ list: vi.fn(),+ get: vi.fn(),+ create: vi.fn(),+ update: vi.fn(),+ delete: vi.fn(),+ },+ },+ auth: {+ refresh: vi.fn(),+ },+};++vi.mock('@spree/sdk', () => ({+ createSpreeClient: vi.fn(() => mockClient),+ SpreeError: class SpreeError extends Error {+ public readonly status: number;+ constructor(response: { error: { message: string } }, status: number) {+ super(response.error.message);+ this.status = status;+ }+ },+}));++import {+ listAddresses,+ getAddress,+ createAddress,+ updateAddress,+ deleteAddress,+} from '../../src/actions/addresses';+import { revalidateTag } from 'next/cache';++// Create a JWT that expires far in the future (no proactive refresh)+function makeFutureJwt(): string {+ const payload = { exp: Math.floor(Date.now() / 1000) + 86400 }; // 24h from now+ return `header.${btoa(JSON.stringify(payload))}.signature`;+}++describe('address actions', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resetClient();+ initSpreeNext({ baseUrl: 'https://api.test.com', apiKey: 'pk_test' });+ // Authenticated user with valid JWT+ mockCookieStore.get.mockReturnValue({ value: makeFutureJwt() });+ });++ describe('listAddresses', () => {+ it('returns addresses list', async () => {+ const mockAddresses = { data: [{ id: '1', firstname: 'John' }] };+ mockClient.customer.addresses.list.mockResolvedValue(mockAddresses);++ const result = await listAddresses();+ expect(result).toEqual(mockAddresses);+ expect(mockClient.customer.addresses.list).toHaveBeenCalledWith(+ undefined,+ expect.objectContaining({ token: expect.any(String) })+ );+ });+ });++ describe('getAddress', () => {+ it('returns a single address', async () => {+ const mockAddress = { id: '1', firstname: 'John', lastname: 'Doe' };+ mockClient.customer.addresses.get.mockResolvedValue(mockAddress);++ const result = await getAddress('1');+ expect(result).toEqual(mockAddress);+ expect(mockClient.customer.addresses.get).toHaveBeenCalledWith(+ '1',+ expect.objectContaining({ token: expect.any(String) })+ );+ });+ });++ describe('createAddress', () => {+ it('creates address and revalidates', async () => {+ const params = {+ firstname: 'Jane',+ lastname: 'Doe',+ address1: '456 Oak Ave',+ city: 'LA',+ zipcode: '90001',+ country_iso: 'US',+ };+ const mockAddress = { id: '2', ...params };+ mockClient.customer.addresses.create.mockResolvedValue(mockAddress);++ const result = await createAddress(params);+ expect(result).toEqual(mockAddress);+ expect(mockClient.customer.addresses.create).toHaveBeenCalledWith(+ params,+ expect.objectContaining({ token: expect.any(String) })+ );+ expect(revalidateTag).toHaveBeenCalledWith('addresses');+ });+ });++ describe('updateAddress', () => {+ it('updates address and revalidates', async () => {+ const params = { firstname: 'Updated' };+ const mockAddress = { id: '1', firstname: 'Updated', lastname: 'Doe' };+ mockClient.customer.addresses.update.mockResolvedValue(mockAddress);++ const result = await updateAddress('1', params);+ expect(result).toEqual(mockAddress);+ expect(mockClient.customer.addresses.update).toHaveBeenCalledWith(+ '1',+ params,+ expect.objectContaining({ token: expect.any(String) })+ );+ expect(revalidateTag).toHaveBeenCalledWith('addresses');+ });+ });++ describe('deleteAddress', () => {+ it('deletes address and revalidates', async () => {+ mockClient.customer.addresses.delete.mockResolvedValue(undefined);++ await deleteAddress('1');+ expect(mockClient.customer.addresses.delete).toHaveBeenCalledWith(+ '1',+ expect.objectContaining({ token: expect.any(String) })+ );+ expect(revalidateTag).toHaveBeenCalledWith('addresses');+ });+ });++ describe('when not authenticated', () => {+ it('throws error', async () => {+ mockCookieStore.get.mockReturnValue(undefined);+ await expect(listAddresses()).rejects.toThrow('Not authenticated');+ });+ });+});diff --git a/packages/next/tests/actions/checkout.test.ts b/packages/next/tests/actions/checkout.test.tsnew file mode 100644index 0000000000..0cfad098b7--- /dev/null+++ b/packages/next/tests/actions/checkout.test.ts@@ -0,0 +1,196 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { mockCookieStore } from '../setup';+import { initSpreeNext, resetClient } from '../../src/config';++const mockClient = {+ orders: {+ get: vi.fn(),+ update: vi.fn(),+ advance: vi.fn(),+ next: vi.fn(),+ complete: vi.fn(),+ shipments: {+ list: vi.fn(),+ update: vi.fn(),+ },+ couponCodes: {+ apply: vi.fn(),+ remove: vi.fn(),+ },+ },+};++vi.mock('@spree/sdk', () => ({+ createSpreeClient: vi.fn(() => mockClient),+}));++import {+ getCheckout,+ updateAddresses,+ advance,+ next,+ getShipments,+ selectShippingRate,+ applyCoupon,+ removeCoupon,+ complete,+} from '../../src/actions/checkout';+import { revalidateTag } from 'next/cache';++describe('checkout actions', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resetClient();+ initSpreeNext({ baseUrl: 'https://api.test.com', apiKey: 'pk_test' });+ // Default: cart token and access token available+ mockCookieStore.get+ .mockReturnValueOnce({ value: 'order_token_123' }) // getCartToken+ .mockReturnValueOnce({ value: 'jwt_token_abc' }); // getAccessToken+ });++ describe('getCheckout', () => {+ it('fetches order with includes and auth options', async () => {+ const mockOrder = { id: '1', number: 'R123', line_items: [{ id: 'li1' }] };+ mockClient.orders.get.mockResolvedValue(mockOrder);++ const result = await getCheckout('1');+ expect(result).toEqual(mockOrder);+ expect(mockClient.orders.get).toHaveBeenCalledWith(+ '1',+ { includes: 'line_items,shipments,ship_address,bill_address' },+ { orderToken: 'order_token_123', token: 'jwt_token_abc' }+ );+ });+ });++ describe('updateAddresses', () => {+ it('updates order addresses and revalidates checkout', async () => {+ const mockOrder = { id: '1', number: 'R123' };+ const addressParams = {+ email: '[email protected]',+ ship_address: { firstname: 'John', lastname: 'Doe', address1: '123 Main St', city: 'NY', zipcode: '10001', country_iso: 'US' },+ };+ mockClient.orders.update.mockResolvedValue(mockOrder);++ const result = await updateAddresses('1', addressParams);+ expect(result).toEqual(mockOrder);+ expect(mockClient.orders.update).toHaveBeenCalledWith(+ '1',+ addressParams,+ { orderToken: 'order_token_123', token: 'jwt_token_abc' }+ );+ expect(revalidateTag).toHaveBeenCalledWith('checkout');+ });+ });++ describe('advance', () => {+ it('advances checkout and revalidates', async () => {+ const mockOrder = { id: '1', state: 'delivery' };+ mockClient.orders.advance.mockResolvedValue(mockOrder);++ const result = await advance('1');+ expect(result).toEqual(mockOrder);+ expect(mockClient.orders.advance).toHaveBeenCalledWith(+ '1',+ { orderToken: 'order_token_123', token: 'jwt_token_abc' }+ );+ expect(revalidateTag).toHaveBeenCalledWith('checkout');+ });+ });++ describe('next', () => {+ it('moves checkout to next step and revalidates', async () => {+ const mockOrder = { id: '1', state: 'payment' };+ mockClient.orders.next.mockResolvedValue(mockOrder);++ const result = await next('1');+ expect(result).toEqual(mockOrder);+ expect(mockClient.orders.next).toHaveBeenCalledWith(+ '1',+ { orderToken: 'order_token_123', token: 'jwt_token_abc' }+ );+ expect(revalidateTag).toHaveBeenCalledWith('checkout');+ });+ });++ describe('getShipments', () => {+ it('returns shipments for the order', async () => {+ const mockShipments = { data: [{ id: 's1', shipping_rates: [] }] };+ mockClient.orders.shipments.list.mockResolvedValue(mockShipments);++ const result = await getShipments('1');+ expect(result).toEqual(mockShipments);+ expect(mockClient.orders.shipments.list).toHaveBeenCalledWith(+ '1',+ { orderToken: 'order_token_123', token: 'jwt_token_abc' }+ );+ });+ });++ describe('selectShippingRate', () => {+ it('selects shipping rate and revalidates checkout', async () => {+ const mockShipment = { id: 's1', selected_shipping_rate_id: 'sr1' };+ mockClient.orders.shipments.update.mockResolvedValue(mockShipment);++ const result = await selectShippingRate('1', 's1', 'sr1');+ expect(result).toEqual(mockShipment);+ expect(mockClient.orders.shipments.update).toHaveBeenCalledWith(+ '1',+ 's1',+ { selected_shipping_rate_id: 'sr1' },+ { orderToken: 'order_token_123', token: 'jwt_token_abc' }+ );+ expect(revalidateTag).toHaveBeenCalledWith('checkout');+ });+ });++ describe('applyCoupon', () => {+ it('applies coupon and revalidates checkout and cart', async () => {+ const mockOrder = { id: '1', promo_total: -10 };+ mockClient.orders.couponCodes.apply.mockResolvedValue(mockOrder);++ const result = await applyCoupon('1', 'SAVE10');+ expect(result).toEqual(mockOrder);+ expect(mockClient.orders.couponCodes.apply).toHaveBeenCalledWith(+ '1',+ 'SAVE10',+ { orderToken: 'order_token_123', token: 'jwt_token_abc' }+ );+ expect(revalidateTag).toHaveBeenCalledWith('checkout');+ expect(revalidateTag).toHaveBeenCalledWith('cart');+ });+ });++ describe('removeCoupon', () => {+ it('removes coupon and revalidates checkout and cart', async () => {+ const mockOrder = { id: '1', promo_total: 0 };+ mockClient.orders.couponCodes.remove.mockResolvedValue(mockOrder);++ const result = await removeCoupon('1', 'promo_1');+ expect(result).toEqual(mockOrder);+ expect(mockClient.orders.couponCodes.remove).toHaveBeenCalledWith(+ '1',+ 'promo_1',+ { orderToken: 'order_token_123', token: 'jwt_token_abc' }+ );+ expect(revalidateTag).toHaveBeenCalledWith('checkout');+ expect(revalidateTag).toHaveBeenCalledWith('cart');+ });+ });++ describe('complete', () => {+ it('completes checkout and revalidates checkout and cart', async () => {+ const mockOrder = { id: '1', state: 'complete' };+ mockClient.orders.complete.mockResolvedValue(mockOrder);++ const result = await complete('1');+ expect(result).toEqual(mockOrder);+ expect(mockClient.orders.complete).toHaveBeenCalledWith(+ '1',+ { orderToken: 'order_token_123', token: 'jwt_token_abc' }+ );+ expect(revalidateTag).toHaveBeenCalledWith('checkout');+ expect(revalidateTag).toHaveBeenCalledWith('cart');+ });+ });+});diff --git a/packages/next/tests/actions/credit-cards.test.ts b/packages/next/tests/actions/credit-cards.test.tsnew file mode 100644index 0000000000..f11c58ac44--- /dev/null+++ b/packages/next/tests/actions/credit-cards.test.ts@@ -0,0 +1,78 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { mockCookieStore } from '../setup';+import { initSpreeNext, resetClient } from '../../src/config';++const mockClient = {+ customer: {+ creditCards: {+ list: vi.fn(),+ delete: vi.fn(),+ },+ },+ auth: {+ refresh: vi.fn(),+ },+};++vi.mock('@spree/sdk', () => ({+ createSpreeClient: vi.fn(() => mockClient),+ SpreeError: class SpreeError extends Error {+ public readonly status: number;+ constructor(response: { error: { message: string } }, status: number) {+ super(response.error.message);+ this.status = status;+ }+ },+}));++import { listCreditCards, deleteCreditCard } from '../../src/actions/credit-cards';+import { revalidateTag } from 'next/cache';++// Create a JWT that expires far in the future+function makeFutureJwt(): string {+ const payload = { exp: Math.floor(Date.now() / 1000) + 86400 };+ return `header.${btoa(JSON.stringify(payload))}.signature`;+}++describe('credit card actions', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resetClient();+ initSpreeNext({ baseUrl: 'https://api.test.com', apiKey: 'pk_test' });+ mockCookieStore.get.mockReturnValue({ value: makeFutureJwt() });+ });++ describe('listCreditCards', () => {+ it('returns credit cards list', async () => {+ const mockCards = { data: [{ id: '1', last_digits: '4242' }] };+ mockClient.customer.creditCards.list.mockResolvedValue(mockCards);++ const result = await listCreditCards();+ expect(result).toEqual(mockCards);+ expect(mockClient.customer.creditCards.list).toHaveBeenCalledWith(+ undefined,+ expect.objectContaining({ token: expect.any(String) })+ );+ });+ });++ describe('deleteCreditCard', () => {+ it('deletes card and revalidates', async () => {+ mockClient.customer.creditCards.delete.mockResolvedValue(undefined);++ await deleteCreditCard('1');+ expect(mockClient.customer.creditCards.delete).toHaveBeenCalledWith(+ '1',+ expect.objectContaining({ token: expect.any(String) })+ );+ expect(revalidateTag).toHaveBeenCalledWith('credit-cards');+ });+ });++ describe('when not authenticated', () => {+ it('throws error', async () => {+ mockCookieStore.get.mockReturnValue(undefined);+ await expect(listCreditCards()).rejects.toThrow('Not authenticated');+ });+ });+});diff --git a/packages/next/tests/actions/gift-cards.test.ts b/packages/next/tests/actions/gift-cards.test.tsnew file mode 100644index 0000000000..fd85e09722--- /dev/null+++ b/packages/next/tests/actions/gift-cards.test.ts@@ -0,0 +1,78 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { mockCookieStore } from '../setup';+import { initSpreeNext, resetClient } from '../../src/config';++const mockClient = {+ customer: {+ giftCards: {+ list: vi.fn(),+ get: vi.fn(),+ },+ },+ auth: {+ refresh: vi.fn(),+ },+};++vi.mock('@spree/sdk', () => ({+ createSpreeClient: vi.fn(() => mockClient),+ SpreeError: class SpreeError extends Error {+ public readonly status: number;+ constructor(response: { error: { message: string } }, status: number) {+ super(response.error.message);+ this.status = status;+ }+ },+}));++import { listGiftCards, getGiftCard } from '../../src/actions/gift-cards';++// Create a JWT that expires far in the future+function makeFutureJwt(): string {+ const payload = { exp: Math.floor(Date.now() / 1000) + 86400 };+ return `header.${btoa(JSON.stringify(payload))}.signature`;+}++describe('gift card actions', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resetClient();+ initSpreeNext({ baseUrl: 'https://api.test.com', apiKey: 'pk_test' });+ mockCookieStore.get.mockReturnValue({ value: makeFutureJwt() });+ });++ describe('listGiftCards', () => {+ it('returns gift cards list', async () => {+ const mockCards = { data: [{ id: '1', code: 'GIFT100', balance: 100 }] };+ mockClient.customer.giftCards.list.mockResolvedValue(mockCards);++ const result = await listGiftCards();+ expect(result).toEqual(mockCards);+ expect(mockClient.customer.giftCards.list).toHaveBeenCalledWith(+ undefined,+ expect.objectContaining({ token: expect.any(String) })+ );+ });+ });++ describe('getGiftCard', () => {+ it('returns a single gift card', async () => {+ const mockCard = { id: '1', code: 'GIFT100', balance: 100 };+ mockClient.customer.giftCards.get.mockResolvedValue(mockCard);++ const result = await getGiftCard('1');+ expect(result).toEqual(mockCard);+ expect(mockClient.customer.giftCards.get).toHaveBeenCalledWith(+ '1',+ expect.objectContaining({ token: expect.any(String) })+ );+ });+ });++ describe('when not authenticated', () => {+ it('throws error', async () => {+ mockCookieStore.get.mockReturnValue(undefined);+ await expect(listGiftCards()).rejects.toThrow('Not authenticated');+ });+ });+});diff --git a/packages/next/tests/actions/orders.test.ts b/packages/next/tests/actions/orders.test.tsnew file mode 100644index 0000000000..8ff2504bc2--- /dev/null+++ b/packages/next/tests/actions/orders.test.ts@@ -0,0 +1,105 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { mockCookieStore } from '../setup';+import { initSpreeNext, resetClient } from '../../src/config';++const mockClient = {+ orders: {+ list: vi.fn(),+ get: vi.fn(),+ },+ auth: {+ refresh: vi.fn(),+ },+};++vi.mock('@spree/sdk', () => ({+ createSpreeClient: vi.fn(() => mockClient),+ SpreeError: class SpreeError extends Error {+ public readonly status: number;+ constructor(response: { error: { message: string } }, status: number) {+ super(response.error.message);+ this.status = status;+ }+ },+}));++import { listOrders, getOrder } from '../../src/actions/orders';++// Create a JWT that expires far in the future+function makeFutureJwt(): string {+ const payload = { exp: Math.floor(Date.now() / 1000) + 86400 };+ return `header.${btoa(JSON.stringify(payload))}.signature`;+}++describe('order actions', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resetClient();+ initSpreeNext({ baseUrl: 'https://api.test.com', apiKey: 'pk_test' });+ mockCookieStore.get.mockReturnValue({ value: makeFutureJwt() });+ });++ describe('listOrders', () => {+ it('returns paginated orders', async () => {+ const mockResponse = {+ data: [{ id: '1', number: 'R001' }],+ meta: { total_count: 1, total_pages: 1 },+ };+ mockClient.orders.list.mockResolvedValue(mockResponse);++ const result = await listOrders({ page: 1 });+ expect(result).toEqual(mockResponse);+ expect(mockClient.orders.list).toHaveBeenCalledWith(+ { page: 1 },+ expect.objectContaining({ token: expect.any(String) })+ );+ });++ it('works without params', async () => {+ const mockResponse = { data: [], meta: { total_count: 0, total_pages: 0 } };+ mockClient.orders.list.mockResolvedValue(mockResponse);++ const result = await listOrders();+ expect(result).toEqual(mockResponse);+ expect(mockClient.orders.list).toHaveBeenCalledWith(+ undefined,+ expect.objectContaining({ token: expect.any(String) })+ );+ });+ });++ describe('getOrder', () => {+ it('returns a single order by id', async () => {+ const mockOrder = { id: '1', number: 'R001', state: 'complete' };+ mockClient.orders.get.mockResolvedValue(mockOrder);++ const result = await getOrder('1');+ expect(result).toEqual(mockOrder);+ expect(mockClient.orders.get).toHaveBeenCalledWith(+ '1',+ undefined,+ expect.objectContaining({ token: expect.any(String) })+ );+ });++ it('passes params through', async () => {+ const mockOrder = { id: '1', number: 'R001' };+ mockClient.orders.get.mockResolvedValue(mockOrder);++ const result = await getOrder('R001', { includes: 'line_items' });+ expect(result).toEqual(mockOrder);+ expect(mockClient.orders.get).toHaveBeenCalledWith(+ 'R001',+ { includes: 'line_items' },+ expect.objectContaining({ token: expect.any(String) })+ );+ });+ });++ describe('when not authenticated', () => {+ it('throws error', async () => {+ mockCookieStore.get.mockReturnValue(undefined);+ await expect(listOrders()).rejects.toThrow('Not authenticated');+ });+ });+});diff --git a/packages/next/tests/auth-helpers.test.ts b/packages/next/tests/auth-helpers.test.tsnew file mode 100644index 0000000000..5ecc9893b0--- /dev/null+++ b/packages/next/tests/auth-helpers.test.ts@@ -0,0 +1,168 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { mockCookieStore } from './setup';+import { initSpreeNext, resetClient } from '../src/config';++const mockClient = {+ auth: {+ refresh: vi.fn(),+ },+};++vi.mock('@spree/sdk', () => {+ class SpreeError extends Error {+ public readonly status: number;+ constructor(response: { error: { message: string } }, status: number) {+ super(response.error.message);+ this.status = status;+ }+ }+ return {+ createSpreeClient: vi.fn(() => mockClient),+ SpreeError,+ };+});++import { getAuthOptions, withAuthRefresh } from '../src/auth-helpers';+import { SpreeError } from '@spree/sdk';++// Helper: create a JWT with a specific expiration time+function makeJwt(expInSeconds: number): string {+ const payload = { exp: expInSeconds };+ return `header.${btoa(JSON.stringify(payload))}.signature`;+}++describe('auth-helpers', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resetClient();+ initSpreeNext({ baseUrl: 'https://api.test.com', apiKey: 'pk_test' });+ });++ describe('getAuthOptions', () => {+ it('returns empty object when no token', async () => {+ mockCookieStore.get.mockReturnValue(undefined);+ const options = await getAuthOptions();+ expect(options).toEqual({});+ });++ it('returns token without refresh when far from expiry', async () => {+ const futureExp = Math.floor(Date.now() / 1000) + 86400; // 24h from now+ const jwt = makeJwt(futureExp);+ mockCookieStore.get.mockReturnValue({ value: jwt });++ const options = await getAuthOptions();+ expect(options).toEqual({ token: jwt });+ expect(mockClient.auth.refresh).not.toHaveBeenCalled();+ });++ it('refreshes token when near expiry', async () => {+ const nearExp = Math.floor(Date.now() / 1000) + 1800; // 30min from now (< 1h)+ const jwt = makeJwt(nearExp);+ const newJwt = 'refreshed_token';+ mockCookieStore.get.mockReturnValue({ value: jwt });+ mockClient.auth.refresh.mockResolvedValue({ token: newJwt });++ const options = await getAuthOptions();+ expect(options).toEqual({ token: newJwt });+ expect(mockClient.auth.refresh).toHaveBeenCalledWith({ token: jwt });+ expect(mockCookieStore.set).toHaveBeenCalledWith(+ '_spree_jwt',+ newJwt,+ expect.any(Object)+ );+ });++ it('uses original token when refresh fails near expiry', async () => {+ const nearExp = Math.floor(Date.now() / 1000) + 1800;+ const jwt = makeJwt(nearExp);+ mockCookieStore.get.mockReturnValue({ value: jwt });+ mockClient.auth.refresh.mockRejectedValue(new Error('Refresh failed'));++ const options = await getAuthOptions();+ expect(options).toEqual({ token: jwt });+ });++ it('uses token as-is when JWT cannot be decoded', async () => {+ const malformedJwt = 'not-a-valid-jwt';+ mockCookieStore.get.mockReturnValue({ value: malformedJwt });++ const options = await getAuthOptions();+ expect(options).toEqual({ token: malformedJwt });+ expect(mockClient.auth.refresh).not.toHaveBeenCalled();+ });+ });++ describe('withAuthRefresh', () => {+ it('throws when not authenticated', async () => {+ mockCookieStore.get.mockReturnValue(undefined);+ const fn = vi.fn();++ await expect(withAuthRefresh(fn)).rejects.toThrow('Not authenticated');+ expect(fn).not.toHaveBeenCalled();+ });++ it('calls fn with auth options and returns result', async () => {+ const futureExp = Math.floor(Date.now() / 1000) + 86400;+ const jwt = makeJwt(futureExp);+ mockCookieStore.get.mockReturnValue({ value: jwt });+ const fn = vi.fn().mockResolvedValue({ data: 'result' });++ const result = await withAuthRefresh(fn);+ expect(result).toEqual({ data: 'result' });+ expect(fn).toHaveBeenCalledWith(expect.objectContaining({ token: jwt }));+ });++ it('retries with refreshed token on 401', async () => {+ const futureExp = Math.floor(Date.now() / 1000) + 86400;+ const jwt = makeJwt(futureExp);+ const newJwt = 'refreshed_token';+ mockCookieStore.get.mockReturnValue({ value: jwt });++ const error401 = new SpreeError({ error: { message: 'Unauthorized' } } as any, 401);+ const fn = vi.fn()+ .mockRejectedValueOnce(error401)+ .mockResolvedValueOnce({ data: 'retried' });+ mockClient.auth.refresh.mockResolvedValue({ token: newJwt });++ const result = await withAuthRefresh(fn);+ expect(result).toEqual({ data: 'retried' });+ expect(fn).toHaveBeenCalledTimes(2);+ expect(fn).toHaveBeenLastCalledWith({ token: newJwt });+ expect(mockCookieStore.set).toHaveBeenCalledWith(+ '_spree_jwt',+ newJwt,+ expect.any(Object)+ );+ });++ it('clears token and rethrows when refresh fails on 401', async () => {+ const futureExp = Math.floor(Date.now() / 1000) + 86400;+ const jwt = makeJwt(futureExp);+ mockCookieStore.get.mockReturnValue({ value: jwt });++ const error401 = new SpreeError({ error: { message: 'Unauthorized' } } as any, 401);+ const fn = vi.fn().mockRejectedValue(error401);+ mockClient.auth.refresh.mockRejectedValue(new Error('Refresh failed'));++ await expect(withAuthRefresh(fn)).rejects.toThrow('Unauthorized');+ // Token should be cleared+ expect(mockCookieStore.set).toHaveBeenCalledWith(+ '_spree_jwt',+ '',+ expect.objectContaining({ maxAge: -1 })+ );+ });++ it('rethrows non-401 errors without refresh', async () => {+ const futureExp = Math.floor(Date.now() / 1000) + 86400;+ const jwt = makeJwt(futureExp);+ mockCookieStore.get.mockReturnValue({ value: jwt });++ const error500 = new Error('Server error');+ const fn = vi.fn().mockRejectedValue(error500);++ await expect(withAuthRefresh(fn)).rejects.toThrow('Server error');+ expect(mockClient.auth.refresh).not.toHaveBeenCalled();+ });+ });+});