# Testing

## API Integration Tests

The primary test suite lives at `packages/backend/api-tests/`. It uses a custom runner that:

1. Creates/migrates a `lunarfront_api_test` database
2. Seeds company, lookup tables, RBAC permissions/roles
3. Starts the backend on port 8001
4. Registers a test user with admin role
5. Runs test suites via HTTP requests
6. Tears down the server

### Running

```bash
cd packages/backend
source .env    # needs DB credentials
bun run api-test
```

### Filtering

```bash
bun run api-test --suite accounts   # run only the accounts suite
bun run api-test --tag crud         # run tests tagged 'crud'
```

### Suites

| Suite | Tests | Coverage |
|-------|-------|----------|
| `accounts` | 17 | CRUD, search, pagination, sort, billing mode |
| `members` | 19 | CRUD, search, move, isMinor, address inheritance |
| `files` | 7 | Upload, list, get, delete, validation, profile pictures |
| `rbac` | 21 | Permission enforcement, role CRUD, user status, pagination |

### Writing Tests

Tests are defined in `api-tests/suites/`. Each file exports a suite:

```typescript
import { suite } from '../lib/context.js'

suite('MyDomain', { tags: ['domain'] }, (t) => {
  t.test('does something', { tags: ['crud'] }, async () => {
    const res = await t.api.post('/v1/endpoint', { name: 'Test' })
    t.assert.status(res, 201)
    t.assert.equal(res.data.name, 'Test')
  })
})
```

Available on `t`:
- `t.api` — HTTP client (`get`, `post`, `patch`, `del`) with auth token
- `t.token` — JWT token string
- `t.baseUrl` — Backend URL
- `t.assert` — Assertion helpers (`status`, `equal`, `ok`, `includes`, `greaterThan`, etc.)

### Assert Methods

| Method | Description |
|--------|-------------|
| `status(res, code)` | Check HTTP status |
| `equal(a, b)` | Strict equality |
| `notEqual(a, b)` | Strict inequality |
| `ok(value)` | Truthy check |
| `includes(arr, value)` | Array includes |
| `contains(str, sub)` | String contains |
| `greaterThan(a, b)` | Numeric comparison |

## Unit Tests

Unit tests use `bun:test` and live alongside the code or in `__tests__/`:

```bash
cd packages/backend
bun run test
```

Current unit test coverage: shared utils (date helpers, currency formatting, state normalization).
