89 lines
2.7 KiB
Markdown
89 lines
2.7 KiB
Markdown
---
|
|
description: "Testing conventions, environment isolation, network mocking, and test hygiene using bun:test"
|
|
globs: "src/**/*.test.ts"
|
|
trigger: "manual"
|
|
---
|
|
|
|
# Testing Conventions & Test Hygiene
|
|
|
|
When writing or modifying automated tests in `src/`:
|
|
|
|
## 1. Test Framework & Colocation
|
|
|
|
- **Runner**: Use `bun:test` primitives (`describe`, `test`, `it`, `expect`, `beforeEach`, `afterEach`).
|
|
- **Colocation**: Place test files directly next to the code they cover using the `*.test.ts` naming convention:
|
|
```text
|
|
src/core/update-cache.ts
|
|
src/core/update-cache.test.ts
|
|
```
|
|
- Do not create isolated `tests/` directories unless testing full external integration fixtures.
|
|
|
|
---
|
|
|
|
## 2. Environment & State Isolation (Zero Leaks)
|
|
|
|
- **Environment Variables**:
|
|
Any test that overrides or adds `process.env` keys MUST restore them in `afterEach()` or a `finally` block:
|
|
```typescript
|
|
const prevEnv = process.env.MY_CUSTOM_VAR;
|
|
try {
|
|
process.env.MY_CUSTOM_VAR = "test-value";
|
|
// test logic
|
|
} finally {
|
|
if (prevEnv !== undefined) {
|
|
process.env.MY_CUSTOM_VAR = prevEnv;
|
|
} else {
|
|
delete process.env.MY_CUSTOM_VAR;
|
|
}
|
|
}
|
|
```
|
|
- **Temporary Files & Directories**:
|
|
Always create isolated temporary workspaces using `mkdtempSync`:
|
|
```typescript
|
|
const testDir = mkdtempSync(join(tmpdir(), "seal-use-test-"));
|
|
try {
|
|
// file operations
|
|
} finally {
|
|
rmSync(testDir, { recursive: true, force: true });
|
|
}
|
|
```
|
|
- **Working Directory (`process.chdir`)**:
|
|
If a test changes cwd, it MUST capture `const cwd = process.cwd();` and restore it in `afterEach()`.
|
|
|
|
---
|
|
|
|
## 3. Network Mocking & Background Child Processes
|
|
|
|
- **HTTP Requests (`fetch`)**:
|
|
- Mock `globalThis.fetch` to isolate tests from live external networks.
|
|
- Wrap mocked fetch cleanly to satisfy Bun/TypeScript types:
|
|
```typescript
|
|
const originalFetch = globalThis.fetch;
|
|
globalThis.fetch = (async () =>
|
|
new Response(JSON.stringify({ ok: true }), {
|
|
status: 200,
|
|
headers: { "Content-Type": "application/json" }
|
|
})
|
|
) as any;
|
|
try {
|
|
// test logic
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
```
|
|
- **Background Processes**:
|
|
- Ensure background asynchronous tasks or detached worker spawns are suppressed in tests:
|
|
```typescript
|
|
process.env.SEAL_DISABLE_BG_UPDATE = "1";
|
|
```
|
|
- This ensures test suites run fast and deterministically without hanging detached workers.
|
|
|
|
---
|
|
|
|
## 4. Test Execution & Quality Verification
|
|
|
|
Before committing changes or opening a PR:
|
|
1. `bun test`: Run all tests (must achieve 100% pass rate).
|
|
2. `bun test <specific.test.ts>`: Target specific files during active development.
|
|
3. `bun run check`: Confirm TypeScript type-checker reports 0 errors.
|