stacks-testing

$npx mdskill add stacksjs/stacks/stacks-testing

Automates test setup and execution for Stacks applications

  • Sets up testing environment including databases and DynamoDB.
  • Deploys tools like @stacksjs/testing to manage tests and utilities.
  • Decides on appropriate test configurations based on database type (SQLite, MySQL) and DynamoDB settings.
  • Delivers executed tests through the test runner, providing results for review.

SKILL.md

.github/skills/stacks-testingView on GitHub ↗
---
name: stacks-testing
description: Use when writing or running tests in Stacks — test setup, database test utilities (setup, refresh, truncate), DynamoDB testing, feature test patterns, the test CLI commands, test configuration in bunfig.toml, or test environment setup. Covers @stacksjs/testing and tests/.
license: MIT
compatibility: Bun >= 1.3.0, TypeScript
allowed-tools: Read Edit Write Bash Grep Glob
---

# Stacks Testing

Uses Bun's built-in test runner with Stacks-specific test utilities.

## Key Paths
- Core package: `storage/framework/core/testing/src/`
- Test directory: `tests/`
- Test setup: `tests/setup.ts`
- Package: `@stacksjs/testing`

## Test Setup

```typescript
import { setupTestEnvironment, setupDatabase, refreshDatabase } from '@stacksjs/testing'

// Set NODE_ENV and APP_ENV to 'test'
setupTestEnvironment()

// Create testing database (SQLite: database/stacks_testing.sqlite)
await setupDatabase()

// Refresh database (drop and re-migrate)
await refreshDatabase()

// Truncate tables
await truncateSqlite()   // for SQLite
await truncateMysql()    // for MySQL
```

## DynamoDB Testing

```typescript
import { launchServer, createStacksTable, deleteStacksTable, delay } from '@stacksjs/testing'

// Launch DynamoDB Local
const { server, endpoint } = await launchServer()

// Create test table
await createStacksTable()

// Cleanup
await deleteStacksTable()

// Utility
await delay(1000)  // wait for async operations
```

## Writing Tests

```typescript
import { describe, test, it, expect, beforeAll, afterAll, beforeEach } from 'bun:test'

describe('User Model', () => {
  beforeAll(async () => {
    await setupDatabase()
  })

  afterAll(async () => {
    await refreshDatabase()
  })

  test('can create a user', async () => {
    const user = await User.create({ name: 'John', email: '[email protected]' })
    expect(user.name).toBe('John')
  })

  test('validates email uniqueness', async () => {
    await expect(User.create({ email: '[email protected]' }))
      .rejects.toThrow()
  })
})
```

## Queue Testing

```typescript
import { fake, restore, runTestJob, expectJobToFail } from '@stacksjs/queue'

test('dispatches welcome email job', async () => {
  const fakeQueue = fake()
  await SendWelcomeEmail.dispatch({ email: '[email protected]' })
  fakeQueue.assertDispatched('SendWelcomeEmail')
  restore()
})
```

## CLI Commands

```bash
buddy test                    # run all tests
buddy test --unit             # unit tests only
buddy test --feature          # feature tests only
bun run test                  # via npm script
bun run test:ui               # UI tests
bun run test:coverage         # with coverage
bun run test:types            # type tests
```

## Configuration (bunfig.toml)

```toml
[test]
preload = ["./tests/setup.ts"]
```

## Test File Conventions
- Test files: `*.test.ts` or `*.spec.ts`
- Located in `tests/` directory
- Setup/teardown in `tests/setup.ts`
- Unit tests in `tests/unit/`
- Feature tests in `tests/feature/`

## Gotchas
- Uses Bun's native test runner, NOT Jest or Vitest
- Test preload runs `tests/setup.ts` before each test file
- SQLite testing database is at `database/stacks_testing.sqlite`
- `refreshDatabase()` drops ALL tables — use in test setup only
- DynamoDB Local must be installed for DynamoDB tests
- Queue testing uses `fake()`/`restore()` pattern — affects global state
- `@stacksjs/faker` provides test data generation
- Coverage reports with `bun run test:coverage`

More from stacksjs/stacks

SkillDescription
stacks-actionsUse when working with Stacks server actions — creating actions in app/Actions/, auto-generated API actions from the useApi model trait, the 80+ default framework actions (auth, dashboard, commerce, content, deployment, jobs), action request/response handling, or action registration. Covers @stacksjs/actions and storage/framework/defaults/actions/.
stacks-aiUse when integrating AI capabilities into a Stacks application — using Anthropic/OpenAI/Ollama/AWS Bedrock drivers, image generation (DALL-E), vision analysis, RAG/vector search, embeddings, MCP (Model Context Protocol) clients, text summarization, sentiment analysis, content classification, personalization, or the buddy AI assistant. Covers @stacksjs/ai and config/ai.ts.
stacks-aliasUse when working with path aliases in a Stacks project — import resolution, module aliasing, or debugging import paths. Covers @stacksjs/alias which defines 260+ path mappings for the entire framework.
stacks-analyticsUse when adding analytics to a Stacks application — configuring Fathom or self-hosted analytics, generating tracking scripts, privacy-friendly analytics setup, or the analytics configuration. Covers @stacksjs/analytics and config/analytics.ts.
stacks-apiUse when building, modifying, or debugging API endpoints in a Stacks application — defining routes, handling requests, API middleware, working with the API server, HTTP client (fetcher), API resources, or OpenAPI generation. Covers both @stacksjs/api utilities and the stacks-api server implementation.
stacks-arraysUse when working with array utilities in Stacks — statistical operations (average, median, mode, standard deviation, z-score, percentile, covariance), array manipulation (unique, flatten, partition, shuffle, sample, move), containment checks, or the Arr facade. Covers @stacksjs/arrays.
stacks-authUse when implementing authentication, authorization, passkeys, TOTP/2FA, RBAC, gates, policies, session auth, token management, email verification, password resets, or rate limiting in a Stacks application. Covers the @stacksjs/auth package, config/auth.ts, app/Gates.ts, and app/Middleware/.
stacks-auto-importsUse when working with the Stacks auto-import system — understanding how browser and server auto-imports work, configuring auto-imported functions/models/composables, the auto-import manifests, type generation, or how globals are injected. Covers the auto-import pipeline at storage/framework/auto-imports/.
stacks-brandkitUse when defining or exploring a brand identity for a Stacks project and you want premium brand-kit REFERENCE IMAGES first - logo directions, palettes, typography specimens, identity boards, and application/mockup decks. Generates IMAGES ONLY, never code. Trained for minimalist, cinematic, editorial, dark-tech, luxury, cultural, security, gaming, developer-tool, and consumer-app brand systems with intentional logo concepting, sparse type, strong symbolic meaning, and disciplined palettes a coding step can build against.
stacks-browseUse for headless browser QA on Stacks applications — navigation, screenshots, responsive testing, console/network monitoring, and accessibility snapshots. Dependency-free: drives a system browser over the Chrome DevTools Protocol using only Bun (no Playwright/Puppeteer). Invoke with /stacks-browse.