> ## Documentation Index
> Fetch the complete documentation index at: https://docs.privacyboost.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Testing

# Testing

This guide covers testing React components that use the Privacy Boost SDK.

## Mock the Hooks, Not the SDK

The hooks subscribe to the SDK's own stores (`sdk.stores`), which are internal
and not something a test can stand in for. A hand-built object passed to
`<PrivacyBoostProvider sdk={...}>` makes every hook throw on its first render.
For unit tests, mock the hooks your components call. Exercise the real SDK in
integration tests against a test deployment.

The examples use Jest and React Testing Library; with Vitest, swap `jest` for
`vi`.

```tsx theme={null}
// Keep the package's real exports and replace only the hooks under test.
jest.mock('@sunnyside-io/privacy-boost-react', () => ({
  ...jest.requireActual('@sunnyside-io/privacy-boost-react'),
  useAuth: jest.fn(),
  useVault: jest.fn(),
  useBalances: jest.fn(),
}));
```

## Testing Components

### Testing useAuth

Build the result from `state`, which is what components should render from. A
returning user is signed in with `locked: true`.

```tsx theme={null}
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { useAuth, type UseAuthResult } from '@sunnyside-io/privacy-boost-react';
import { WalletButton } from '../components/WalletButton';

function mockAuth(overrides: Partial<UseAuthResult>) {
  jest.mocked(useAuth).mockReturnValue({
    state: { status: 'signedOut' },
    status: 'disconnected',
    privacyAddress: null,
    signInWithWalletAdapter: jest.fn(),
    ...overrides,
  } as Partial<UseAuthResult> as UseAuthResult);
}

describe('WalletButton', () => {
  it('shows the sign-in button when signed out', () => {
    mockAuth({});
    render(<WalletButton />);

    expect(screen.getByText('Sign in')).toBeInTheDocument();
  });

  it('shows the privacy address on a locked session', () => {
    mockAuth({
      status: 'locked',
      state: {
        status: 'signedIn',
        locked: true,
        account: { walletAddress: '0x123', privacyAddress: '0x04abc123', mpk: '0x1' },
      },
      privacyAddress: '0x04abc123',
    });
    render(<WalletButton />);

    expect(screen.getByText(/0x04abc123/)).toBeInTheDocument();
  });

  it('signs in on click', async () => {
    const signInWithWalletAdapter = jest.fn().mockResolvedValue({ status: 'signedIn' });
    mockAuth({ signInWithWalletAdapter });
    render(<WalletButton />);

    fireEvent.click(screen.getByText('Sign in'));

    await waitFor(() => {
      expect(signInWithWalletAdapter).toHaveBeenCalled();
    });
  });
});
```

### Testing useVault

```tsx theme={null}
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { useVault } from '@sunnyside-io/privacy-boost-react';
import { ShieldForm } from '../components/ShieldForm';

function mockVault(overrides: Partial<ReturnType<typeof useVault>>) {
  jest.mocked(useVault).mockReturnValue({
    shield: jest.fn(),
    refreshBalances: jest.fn().mockResolvedValue(undefined),
    ...overrides,
  } as Partial<ReturnType<typeof useVault>> as ReturnType<typeof useVault>);
}

describe('ShieldForm', () => {
  it('calls shield with correct params', async () => {
    const shield = jest.fn().mockResolvedValue({ txHash: '0x1', requestId: 'req-1' });
    mockVault({ shield });
    render(<ShieldForm tokenAddress="0xtoken" />);

    fireEvent.change(screen.getByPlaceholderText('Amount'), { target: { value: '1.5' } });
    fireEvent.click(screen.getByText('Deposit'));

    await waitFor(() => {
      expect(shield).toHaveBeenCalledWith({
        tokenAddress: '0xtoken',
        amount: '1.5',
        onProgress: expect.any(Function),
      });
    });
  });

  it('shows error on failure', async () => {
    const shield = jest.fn().mockRejectedValue(new Error('Insufficient balance'));
    mockVault({ shield });
    render(<ShieldForm tokenAddress="0xtoken" />);

    fireEvent.change(screen.getByPlaceholderText('Amount'), { target: { value: '100' } });
    fireEvent.click(screen.getByText('Deposit'));

    await waitFor(() => {
      expect(screen.getByText(/Insufficient balance/)).toBeInTheDocument();
    });
  });
});
```

To assert on a specific error code, reject with a real `PrivacyBoostError`:
`new PrivacyBoostError(ErrorCodes.TRANSACTION_REJECTED, 'declined')`.

### Testing useBalances

```tsx theme={null}
import { render, screen } from '@testing-library/react';
import { useBalances, type FormattedBalance } from '@sunnyside-io/privacy-boost-react';
import { BalanceList } from '../components/BalanceList';

describe('BalanceList', () => {
  it('displays balances', () => {
    const usdc: FormattedBalance = {
      tokenAddress: '0x0000000000000000000000000000000000000001',
      symbol: 'USDC',
      decimals: 6,
      shieldedBalance: 1_000_000n,
      walletBalance: 500_000n,
      formattedShielded: '1.0',
      formattedWallet: '0.5',
    };
    jest.mocked(useBalances).mockReturnValue({
      balances: [usdc],
      loading: false,
      tokenCount: 1,
      lastSynced: Date.now(),
    } as Partial<ReturnType<typeof useBalances>> as ReturnType<typeof useBalances>);

    render(<BalanceList />);

    expect(screen.getByText('USDC')).toBeInTheDocument();
    expect(screen.getByText('1.0')).toBeInTheDocument();
  });
});
```

## Testing Hooks

### Custom Hook Testing

A custom hook built on the SDK hooks, such as `useDepositFlow` from
[Custom Hooks](https://docs.privacyboost.io/sdk/react/advanced/custom-hooks.md), is tested the same way: mock what it calls.

```tsx theme={null}
import { renderHook, act } from '@testing-library/react';
import { useAuth, useVault, type UseAuthResult } from '@sunnyside-io/privacy-boost-react';
import { useDepositFlow } from '../hooks/useDepositFlow';

describe('useDepositFlow', () => {
  it('handles shield flow', async () => {
    const shield = jest.fn().mockResolvedValue({ txHash: '0xabc', requestId: 'req-1' });
    jest.mocked(useVault).mockReturnValue(
      { shield } as Partial<ReturnType<typeof useVault>> as ReturnType<typeof useVault>,
    );
    jest.mocked(useAuth).mockReturnValue({
      state: {
        status: 'signedIn',
        locked: true,
        account: { walletAddress: '0x123', privacyAddress: '0x04abc', mpk: '0x1' },
      },
    } as Partial<UseAuthResult> as UseAuthResult);

    const { result } = renderHook(() => useDepositFlow());

    expect(result.current.loading).toBe(false);

    await act(async () => {
      await result.current.shield('0xtoken', '1.0');
    });

    expect(shield).toHaveBeenCalled();
    expect(result.current.txHash).toBe('0xabc');
  });
});
```

## Mocking window\.ethereum

`signInWithWalletAdapter` builds its adapter from `window.ethereum`. When a test
renders the real `useAuth` against a mocked wallet, stub the provider:

```tsx theme={null}
beforeEach(() => {
  Object.defineProperty(window, 'ethereum', {
    value: {
      isMetaMask: true,
      request: jest.fn(),
      on: jest.fn(),
      removeListener: jest.fn(),
    },
    writable: true,
    configurable: true,
  });
});

afterEach(() => {
  delete window.ethereum;
});
```

## Next Steps

* [Custom Hooks](https://docs.privacyboost.io/sdk/react/advanced/custom-hooks.md)
* [SSR Support](https://docs.privacyboost.io/sdk/react/advanced/ssr-support.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.