Hamster Sync Integration Testing
Overview
apps/sync integration tests are not generic NestJS integration tests. The established repo pattern is:
- use real Redis + real local Supabase
- boot a real
SyncEngineModule test app
- replace BullMQ workers with UUID-suffixed test queues
- mock Linear only with MSW
- drain queue jobs deterministically inside the test instead of relying on live workers
This skill exists to keep new sync integration tests aligned with that architecture.
Use This Skill When
- Adding or editing
apps/sync/src/**/*.integration.spec.ts
- Writing tests for Linear webhook ingress, inbound sync, outbound sync, reconciliation, or connection lifecycle flows
- Adding MSW handlers or Linear GraphQL overrides for sync tests
- Debugging a flaky or incomplete sync integration test
- Choosing the right sync test harness or spec family for a runtime change
Core Rules
- Keep the boundary honest
- Integration tests trust DB contracts from
apps/web and focus on the sync runtime: controller -> queue -> consumer -> orchestrator -> DB state.
- Do not replace Supabase or Redis with mocks in sync integration specs.
- If the behavior under test depends on RLS, triggers, outbox RPCs, or DB constraints, inspect the matching
apps/web/test/database/** or pgTAP files instead of re-testing the same contract indirectly.
- Mock only Linear
- Use
setupMswTestServer() from test/msw/server.ts.
- Default mode is
strict-linear: unexpected Linear calls fail, local traffic is allowed through.
- Add shared handlers to
linearBaseHandlers only when the operation is broadly reused. Use testServer.use(...) for one-off behavior.
- Use the right harness (see Quick Reference table below)
createInboundAppHarness() for webhook + inbound queue tests
createOutboxHarness() for outbound event and provider mutation tests (disables background polling automatically)
createSyncAppHarness() for controller, reconciliation, and general multi-queue flows
- Process queues manually
- Use
processWebhookAndInboundJobs, processOutboundJobs, or processReconciliationAndInboundJobs.
- Do not rely on background BullMQ workers starting inside the tests.
- Preserve deterministic cleanup
- Use
runIntegrationSpecAfterEach(...) in full-runtime/MSW specs so cleanup failures do not hide MSW unhandled-request failures.
- Focused ingress or worker specs may use bespoke cleanup instead when they do not boot the shared runtime harness.
- Never reuse a BullMQ queue across tests.
- Assert runtime side effects, not only HTTP status
- Check domain rows (
tasks, brief, initiatives)
- Check
sync_entity_mappings
- Check
sync_logs
- Check
sync_outbound_events when relevant
Quick Reference
| Runtime area changed |
Start from |
Harness / helpers |
webhooks/linear-webhook.controller.ts |
webhooks/linear-webhook.controller.integration.spec.ts |
focused test module + createTestQueue, cleanupQueue |
queues/webhook.consumer.ts, queues/inbound-sync.consumer.ts |
integration/bidirectional-*.integration.spec.ts |
createInboundAppHarness, postLinearWebhook, setWebhookSecret, processWebhookAndInboundJobs |
queues/outbound-sync.consumer.ts, services/outbox-worker.service.ts |
integration/outbound-operational.integration.spec.ts or outbound sections in bidirectional-*.integration.spec.ts |
createOutboxHarness, clearOutboundEvents, insertOutboundEvent, processOutboundJobs |
| Outbox claiming, lease handling, dedupe, job-ID generation |
services/outbound-event-worker.integration.spec.ts or services/outbox-worker.integration.spec.ts |
focused worker/service setup, direct service invocation, queue assertions |
queues/reconciliation.consumer.ts |
integration/reconciliation-operational.integration.spec.ts |
createSyncAppHarness, createHeaders, processReconciliationAndInboundJobs |
controllers/sync-connections.controller.ts |
controllers/sync-connections.controller.integration.spec.ts |
createSyncAppHarness({ useTestAuthGuard: true, useValidationPipe: true }), request(...), queue assertions |
adapters/linear/* |
providers/linear-provider.integration.spec.ts or adapter-specific integration specs |
direct adapter tests + testServer.use(...) overrides |
| Document polling / retry / user mapping refresh / retention cleanup |
matching queues/*.integration.spec.ts |
createSyncAppHarness and the specific queue under test |
| Orchestration of task / brief / initiative entities |
relevant bidirectional-*.integration.spec.ts |
createInboundAppHarness or createOutboxHarness depending on direction |
Canonical Source Files
All paths in this section are relative to apps/sync/. Read these before editing tests:
| File |
What to look for |
apps/sync/TESTING.md |
Authoritative test guide — prerequisites, architecture, MSW harness, fixtures, troubleshooting |
test/helpers/bidirectional-integration-helpers.ts |
All harness factories, job-processing helpers, actor management, cleanup, auth headers |
test/helpers/supabase-helpers.ts |
Seed functions, query helpers, outbox management, admin client factory |
test/helpers/bullmq-helpers.ts |
Queue creation with UUID suffix, job completion waiting, cleanup |
test/msw/server.ts |
MSW server factory with strict-linear mode |
test/msw/linear-handlers.ts |
Base handlers for all Linear operations, override factories, error fixtures |
test/fixtures/linear-responses.ts |
Factory functions for Linear response shapes, webhook payloads, signLinearWebhook |
Representative specs (read the one closest to your change before writing new tests):
integration/bidirectional-task-sync.integration.spec.ts
integration/bidirectional-brief-sync.integration.spec.ts
integration/bidirectional-initiative-sync.integration.spec.ts
integration/outbound-operational.integration.spec.ts
integration/reconciliation-operational.integration.spec.ts
controllers/sync-connections.controller.integration.spec.ts
webhooks/linear-webhook.controller.integration.spec.ts
services/outbound-event-worker.integration.spec.ts
services/outbox-worker.integration.spec.ts
msw-interception.integration.spec.ts
Related DB contract tests to consult when the runtime change depends on DB behavior:
apps/web/test/database/**
apps/web/supabase/tests/database/**
Test Selection Workflow
- Find the matching row in the Quick Reference table above.
- Clone the nearest existing test shape — do not invent a fresh test harness if the target entity already has a matching bidirectional or operational spec.
- Choose the narrowest seam that proves the behavior:
- Need webhook ingress + HMAC + queue enqueue? test the controller.
- Need provider -> local convergence? use inbound webhook + inbound queue.
- Need local -> provider mutation? seed outbox state and drive outbound processing.
- Need resync / page walking behavior? use reconciliation HTTP flow.
- Need exact GraphQL variable shape? test the adapter directly or capture variables via MSW in an outbound canary.
New Test Skeleton
Use this as the starting template for a new bidirectional integration spec.
import { HttpResponse } from 'msw';
import {
createLinearIssue, // or createLinearProject, createLinearInitiative
createLinearWebhookPayload,
} from '../../../../test/fixtures/linear-responses';
import {
TEST_WEBHOOK_SECRET,
type TestActor,
createActor,
createInboundAppHarness,
linearProviderConfig,
postLinearWebhook,
processWebhookAndInboundJobs,
runIntegrationSpecAfterEach,
setWebhookSecret,
} from '../../../../test/helpers/bidirectional-integration-helpers';
import {
createTestSupabaseAdmin,
querySyncLogs,
seedSyncConnection,
} from '../../../../test/helpers/supabase-helpers';
import {
createLinearQueryOverride,
} from '../../../../test/msw/linear-handlers';
import { setupMswTestServer, testServer } from '../../../../test/msw/server';
import { randomUUID } from 'crypto';
// vi.hoisted runs before module loading — required because the sync engine
// calls getConnectionProviderCredentials at runtime to resolve both webhook
// secrets (inbound) and provider access tokens (outbound/reconciliation).
const vaultCredentialsMock = vi.hoisted(() => vi.fn());
vi.mock('@kit/supabase/vault-connection-credentials', async () => {
const actual = await vi.importActual<
typeof import('@kit/supabase/vault-connection-credentials')
>('@kit/supabase/vault-connection-credentials');
return {
...actual,
getConnectionProviderCredentials: vaultCredentialsMock,
};
});
const msw = setupMswTestServer();
const ACTOR_EMAIL_PREFIX = 'my-entity-sync'; // keep unique across spec files
describe('My entity sync (integration)', () => {
const supabase = createTestSupabaseAdmin();
const actorsForCleanup: TestActor[] = [];
const accountIdsForSyncCleanup = new Set<string>();
beforeAll(msw.beforeAll);
beforeEach(() => {
vi.stubEnv('SYNC_ENGINE_ENABLED', 'true');
vi.stubEnv('SYNC_OUTBOUND_ENABLED', 'true');
vi.stubEnv(
'NEXT_PUBLIC_SUPABASE_URL',
process.env.NEXT_PUBLIC_SUPABASE_URL ?? process.env.SUPABASE_URL ?? '',
);
// For inbound specs use TEST_WEBHOOK_SECRET; for outbound/reconciliation
// specs use serializeStoredProviderCredentials({access_token: ...}).
vaultCredentialsMock.mockResolvedValue(TEST_WEBHOOK_SECRET);
msw.beforeEach();
});
afterEach(async () => {
vi.unstubAllEnvs();
await runIntegrationSpecAfterEach({
supabase,
actors: actorsForCleanup,
accountIdsForSyncCleanup,
msw,
});
});
afterAll(msw.afterAll);
it('Inbound: creates entity from webhook', async () => {
const actor = await createActor(ACTOR_EMAIL_PREFIX);
actorsForCleanup.push(actor);
accountIdsForSyncCleanup.add(actor.accountId);
const { connection } = await seedSyncConnection(
{
accountId: actor.accountId,
createdBy: actor.userId,
syncEnabled: true,
providerConfig: linearProviderConfig,
},
supabase,
);
const connectionId = String(connection.id);
await setWebhookSecret(connectionId);
const harness = await createInboundAppHarness();
try {
testServer.use(
createLinearQueryOverride('IssueById', async ({ variables }) => {
return HttpResponse.json({
data: {
issue: createLinearIssue({
id: (variables.id as string) ?? 'linear-issue-1',
title: 'Expected title',
}),
},
});
}),
);
const payload = createLinearWebhookPayload(
'Issue',
'create',
createLinearIssue({ id: 'linear-issue-1', title: 'Expected title' }),
);
const response = await postLinearWebhook({
app: harness.app,
accountId: actor.accountId,
connectionId,
payload,
deliveryId: `delivery-${randomUUID()}`,
});
expect(response.status).toBe(200);
await processWebhookAndInboundJobs({
moduleRef: harness.moduleRef,
webhookQueue: harness.webhookQueue,
inboundQueue: harness.inboundQueue,
});
// Assert domain row
const { data: rows } = await supabase
.from('tasks')
.select('id,title,status')
.eq('account_id', actor.accountId)
.eq('title', 'Expected title')
.limit(1);
expect(rows).toHaveLength(1);
// Assert mapping
const { data: mapping } = await supabase
.from('sync_entity_mappings')
.select('external_entity_type,external_id,hamster_entity_type,hamster_id')
.eq('sync_connection_id', connectionId)
.eq('external_id', 'linear-issue-1')
.single();
expect(mapping?.hamster_entity_type).toBe('task');
expect(mapping?.hamster_id).toBe(rows?.[0]?.id);
// Assert sync log
const logs = await querySyncLogs(
connectionId,
{ direction: 'inbound', entityType: 'issue' },
supabase,
);
expect(
logs.filter((l) => l.operation === 'create' && l.status === 'success'),
).toHaveLength(1);
} finally {
await harness.cleanup();
}
});
});
Skeleton conventions
- Vault mock with
vi.hoisted: every bidirectional spec needs this. For outbound/reconciliation specs, mock with serializeStoredProviderCredentials({access_token: ...}) instead of TEST_WEBHOOK_SECRET.
linearProviderConfig: canonical Linear config from bidirectional-integration-helpers.ts. Use it so status mapping, team ID, and workspace config match what MSW base handlers expect.
- Actor tracking: push every actor to
actorsForCleanup and add the account ID to accountIdsForSyncCleanup immediately after creation.
try / finally around harness: always clean up even if the test throws — leaked Redis connections cause "Connection is closed" errors in subsequent tests.
String(connection.id): connection IDs from Supabase are typed string | number. Cast once at the top.
Full-runtime harnesses vs focused worker specs
- Full-runtime sync specs boot
SyncEngineModule, use real Supabase + Redis, and often use MSW at the Linear boundary. These are the bidirectional-*.integration.spec.ts, outbound-operational, reconciliation-operational, and sync-connections.controller specs.
- Focused worker/service integration specs exercise one worker or service with real queue/storage seams but without the full shared app harness. These are
outbound-event-worker.integration.spec.ts, outbox-worker.integration.spec.ts, etc.
Use the focused specs when the behavior under test is primarily about outbox claiming, lease handling, dedupe, or deterministic job construction. Do not force those cases into the larger operational canary shape.
Loop suppression and sync markers
This repo uses sync_entity_mappings.last_sync_origin and last_sync_applied_at to suppress immediate echo loops. When testing follow-up inbound or outbound behavior:
- prefer directly nulling or backdating those fields in test setup
- avoid
sleep or arbitrary timeouts to wait out the suppression window
// Deactivate suppression for a follow-up inbound update test
await supabase
.from('sync_entity_mappings')
.update({ last_sync_origin: null, last_sync_applied_at: null })
.eq('sync_connection_id', connectionId)
.eq('external_id', 'linear-issue-1');
NULL values in both fields bypass the check entirely.
MSW and Fixtures
See apps/sync/TESTING.md for the full MSW setup reference, fixture factory list, and error helper catalog.
Key decision rules:
- Add to
linearBaseHandlers when the same Linear operation will be used across several tests.
- Use
createLinearQueryOverride or createLinearMutationOverride when the behavior is specific to one test.
- Base handlers intentionally validate minimal required inputs (e.g.
IssueCreate rejects missing title or teamId). Do not weaken them to make a test pass — override the operation instead.
- Service-level integration tests use MSW. Lower-level adapter or service unit specs use direct
vi.stubGlobal('fetch', ...). Default to MSW + harness for sync integration tests.
Assertions That Matter
Prefer these repo-native assertions over shallow status checks:
- domain row updated in the correct table
- mapping row exists and points to the expected
hamster_id / external_id
sync_logs contains the expected direction, entity_type, operation, and status
sync_outbound_events.processed_at changed when testing outbound completion
- relevant queue received the right job name when testing HTTP flows
For initiative-related sync, remember that initiative_briefs is the canonical relationship set. When a change affects initiative/project linkage, assert the canonical link rows instead of treating brief.initiative_id as the primary contract.
Anti-Patterns
- Do not mock Supabase or Redis in sync integration tests.
- Do not put new sync integration tests outside
apps/sync/src/**/*.integration.spec.ts.
- Do not use arbitrary sleeps for queue or suppression timing.
- Do not reuse a queue after cleanup; create fresh queues in
beforeEach.
- Do not bypass unexpected Linear requests with
'bypass' unless the test explicitly needs it.
- Do not assert only the local entity row when mappings or sync logs are the real contract.
- Do not forget
clearOutboundEvents(...) before asserting update/delete outbox events for an entity that was just inserted.
- Do not pass
accountId where a real auth user ID is required (for example initiatives.owner_id references auth.users.id).
- Do not forget
vi.unstubAllEnvs() in afterEach — env stubs leak across tests without it.
- Do not skip the vault credentials mock — the sync engine calls
getConnectionProviderCredentials to resolve both webhook secrets and provider tokens.
- Do not forget
try / finally around harness usage — leaked Redis connections cause "Connection is closed" errors in subsequent tests.
Verification
Run the smallest useful test first:
pnpm --filter sync exec vitest run --config vitest.config.integration.ts \
apps/sync/src/modules/sync-engine/<path-to-spec>.integration.spec.ts
Then run the full integration suite when the change affects shared helpers, MSW setup, queue wiring, or multiple spec families:
pnpm --filter sync test:integration
If runtime code changed alongside tests, also run:
pnpm --filter sync typecheck
If the change touches shared helpers, queue wiring, or sync runtime code beyond a narrow test-only edit, also run:
pnpm --filter sync build
1---2name: hamster-sync-integration-testing3description: "Deterministic integration testing patterns for `apps/sync`. Use this whenever you need to add, modify, review, or debug sync integration tests, especially if the work involves MSW mocks, Linear webhooks, queue consumers, reconciliation, connection lifecycle HTTP flows, or bidirectional task/brief/initiative sync. This skill should win over generic testing advice whenever the user mentions `apps/sync`, `.integration.spec.ts`, Linear mocking, webhook tests, or sync runtime canaries."4version: "1.0.0"5metadata:6 source: https://skillmd.com/skills/gethamster/hamster-sync-integration-testing7---89# Hamster Sync Integration Testing1011## Overview1213`apps/sync` integration tests are **not** generic NestJS integration tests. The established repo pattern is:1415- use **real Redis + real local Supabase**16- boot a **real `SyncEngineModule` test app**17- replace BullMQ workers with **UUID-suffixed test queues**18- mock **Linear only** with MSW19- drain queue jobs **deterministically inside the test** instead of relying on live workers2021This skill exists to keep new sync integration tests aligned with that architecture.2223## Use This Skill When2425- Adding or editing `apps/sync/src/**/*.integration.spec.ts`26- Writing tests for Linear webhook ingress, inbound sync, outbound sync, reconciliation, or connection lifecycle flows27- Adding MSW handlers or Linear GraphQL overrides for sync tests28- Debugging a flaky or incomplete sync integration test29- Choosing the right sync test harness or spec family for a runtime change3031## Core Rules32331. **Keep the boundary honest**3435- Integration tests trust DB contracts from `apps/web` and focus on the sync runtime: controller -> queue -> consumer -> orchestrator -> DB state.36- Do not replace Supabase or Redis with mocks in sync integration specs.37- If the behavior under test depends on RLS, triggers, outbox RPCs, or DB constraints, inspect the matching `apps/web/test/database/**` or pgTAP files instead of re-testing the same contract indirectly.38392. **Mock only Linear**4041- Use `setupMswTestServer()` from `test/msw/server.ts`.42- Default mode is `strict-linear`: unexpected Linear calls fail, local traffic is allowed through.43- Add shared handlers to `linearBaseHandlers` only when the operation is broadly reused. Use `testServer.use(...)` for one-off behavior.44453. **Use the right harness** (see Quick Reference table below)4647- `createInboundAppHarness()` for webhook + inbound queue tests48- `createOutboxHarness()` for outbound event and provider mutation tests (disables background polling automatically)49- `createSyncAppHarness()` for controller, reconciliation, and general multi-queue flows50514. **Process queues manually**5253- Use `processWebhookAndInboundJobs`, `processOutboundJobs`, or `processReconciliationAndInboundJobs`.54- Do not rely on background BullMQ workers starting inside the tests.55565. **Preserve deterministic cleanup**5758- Use `runIntegrationSpecAfterEach(...)` in full-runtime/MSW specs so cleanup failures do not hide MSW unhandled-request failures.59- Focused ingress or worker specs may use bespoke cleanup instead when they do not boot the shared runtime harness.60- Never reuse a BullMQ queue across tests.61626. **Assert runtime side effects, not only HTTP status**6364- Check domain rows (`tasks`, `brief`, `initiatives`)65- Check `sync_entity_mappings`66- Check `sync_logs`67- Check `sync_outbound_events` when relevant6869## Quick Reference7071| Runtime area changed | Start from | Harness / helpers |72| --- | --- | --- |73| `webhooks/linear-webhook.controller.ts` | `webhooks/linear-webhook.controller.integration.spec.ts` | focused test module + `createTestQueue`, `cleanupQueue` |74| `queues/webhook.consumer.ts`, `queues/inbound-sync.consumer.ts` | `integration/bidirectional-*.integration.spec.ts` | `createInboundAppHarness`, `postLinearWebhook`, `setWebhookSecret`, `processWebhookAndInboundJobs` |75| `queues/outbound-sync.consumer.ts`, `services/outbox-worker.service.ts` | `integration/outbound-operational.integration.spec.ts` or outbound sections in `bidirectional-*.integration.spec.ts` | `createOutboxHarness`, `clearOutboundEvents`, `insertOutboundEvent`, `processOutboundJobs` |76| Outbox claiming, lease handling, dedupe, job-ID generation | `services/outbound-event-worker.integration.spec.ts` or `services/outbox-worker.integration.spec.ts` | focused worker/service setup, direct service invocation, queue assertions |77| `queues/reconciliation.consumer.ts` | `integration/reconciliation-operational.integration.spec.ts` | `createSyncAppHarness`, `createHeaders`, `processReconciliationAndInboundJobs` |78| `controllers/sync-connections.controller.ts` | `controllers/sync-connections.controller.integration.spec.ts` | `createSyncAppHarness({ useTestAuthGuard: true, useValidationPipe: true })`, `request(...)`, queue assertions |79| `adapters/linear/*` | `providers/linear-provider.integration.spec.ts` or adapter-specific integration specs | direct adapter tests + `testServer.use(...)` overrides |80| Document polling / retry / user mapping refresh / retention cleanup | matching `queues/*.integration.spec.ts` | `createSyncAppHarness` and the specific queue under test |81| Orchestration of task / brief / initiative entities | relevant `bidirectional-*.integration.spec.ts` | `createInboundAppHarness` or `createOutboxHarness` depending on direction |8283## Canonical Source Files8485All paths in this section are relative to `apps/sync/`. Read these before editing tests:8687| File | What to look for |88| --- | --- |89| `apps/sync/TESTING.md` | Authoritative test guide — prerequisites, architecture, MSW harness, fixtures, troubleshooting |90| `test/helpers/bidirectional-integration-helpers.ts` | All harness factories, job-processing helpers, actor management, cleanup, auth headers |91| `test/helpers/supabase-helpers.ts` | Seed functions, query helpers, outbox management, admin client factory |92| `test/helpers/bullmq-helpers.ts` | Queue creation with UUID suffix, job completion waiting, cleanup |93| `test/msw/server.ts` | MSW server factory with `strict-linear` mode |94| `test/msw/linear-handlers.ts` | Base handlers for all Linear operations, override factories, error fixtures |95| `test/fixtures/linear-responses.ts` | Factory functions for Linear response shapes, webhook payloads, `signLinearWebhook` |9697Representative specs (read the one closest to your change before writing new tests):9899- `integration/bidirectional-task-sync.integration.spec.ts`100- `integration/bidirectional-brief-sync.integration.spec.ts`101- `integration/bidirectional-initiative-sync.integration.spec.ts`102- `integration/outbound-operational.integration.spec.ts`103- `integration/reconciliation-operational.integration.spec.ts`104- `controllers/sync-connections.controller.integration.spec.ts`105- `webhooks/linear-webhook.controller.integration.spec.ts`106- `services/outbound-event-worker.integration.spec.ts`107- `services/outbox-worker.integration.spec.ts`108- `msw-interception.integration.spec.ts`109110Related DB contract tests to consult when the runtime change depends on DB behavior:111112- `apps/web/test/database/**`113- `apps/web/supabase/tests/database/**`114115## Test Selection Workflow1161171. **Find the matching row** in the Quick Reference table above.1182. **Clone the nearest existing test shape** — do not invent a fresh test harness if the target entity already has a matching bidirectional or operational spec.1193. **Choose the narrowest seam** that proves the behavior:120121- Need webhook ingress + HMAC + queue enqueue? test the controller.122- Need provider -> local convergence? use inbound webhook + inbound queue.123- Need local -> provider mutation? seed outbox state and drive outbound processing.124- Need resync / page walking behavior? use reconciliation HTTP flow.125- Need exact GraphQL variable shape? test the adapter directly or capture variables via MSW in an outbound canary.126127## New Test Skeleton128129Use this as the starting template for a new bidirectional integration spec.130131```typescript132import { HttpResponse } from 'msw';133134import {135 createLinearIssue, // or createLinearProject, createLinearInitiative136 createLinearWebhookPayload,137} from '../../../../test/fixtures/linear-responses';138import {139 TEST_WEBHOOK_SECRET,140 type TestActor,141 createActor,142 createInboundAppHarness,143 linearProviderConfig,144 postLinearWebhook,145 processWebhookAndInboundJobs,146 runIntegrationSpecAfterEach,147 setWebhookSecret,148} from '../../../../test/helpers/bidirectional-integration-helpers';149import {150 createTestSupabaseAdmin,151 querySyncLogs,152 seedSyncConnection,153} from '../../../../test/helpers/supabase-helpers';154import {155 createLinearQueryOverride,156} from '../../../../test/msw/linear-handlers';157import { setupMswTestServer, testServer } from '../../../../test/msw/server';158159import { randomUUID } from 'crypto';160161// vi.hoisted runs before module loading — required because the sync engine162// calls getConnectionProviderCredentials at runtime to resolve both webhook163// secrets (inbound) and provider access tokens (outbound/reconciliation).164const vaultCredentialsMock = vi.hoisted(() => vi.fn());165166vi.mock('@kit/supabase/vault-connection-credentials', async () => {167 const actual = await vi.importActual<168 typeof import('@kit/supabase/vault-connection-credentials')169 >('@kit/supabase/vault-connection-credentials');170171 return {172 ...actual,173 getConnectionProviderCredentials: vaultCredentialsMock,174 };175});176177const msw = setupMswTestServer();178const ACTOR_EMAIL_PREFIX = 'my-entity-sync'; // keep unique across spec files179180describe('My entity sync (integration)', () => {181 const supabase = createTestSupabaseAdmin();182 const actorsForCleanup: TestActor[] = [];183 const accountIdsForSyncCleanup = new Set<string>();184185 beforeAll(msw.beforeAll);186187 beforeEach(() => {188 vi.stubEnv('SYNC_ENGINE_ENABLED', 'true');189 vi.stubEnv('SYNC_OUTBOUND_ENABLED', 'true');190 vi.stubEnv(191 'NEXT_PUBLIC_SUPABASE_URL',192 process.env.NEXT_PUBLIC_SUPABASE_URL ?? process.env.SUPABASE_URL ?? '',193 );194195 // For inbound specs use TEST_WEBHOOK_SECRET; for outbound/reconciliation196 // specs use serializeStoredProviderCredentials({access_token: ...}).197 vaultCredentialsMock.mockResolvedValue(TEST_WEBHOOK_SECRET);198 msw.beforeEach();199 });200201 afterEach(async () => {202 vi.unstubAllEnvs();203204 await runIntegrationSpecAfterEach({205 supabase,206 actors: actorsForCleanup,207 accountIdsForSyncCleanup,208 msw,209 });210 });211212 afterAll(msw.afterAll);213214 it('Inbound: creates entity from webhook', async () => {215 const actor = await createActor(ACTOR_EMAIL_PREFIX);216 actorsForCleanup.push(actor);217 accountIdsForSyncCleanup.add(actor.accountId);218219 const { connection } = await seedSyncConnection(220 {221 accountId: actor.accountId,222 createdBy: actor.userId,223 syncEnabled: true,224 providerConfig: linearProviderConfig,225 },226 supabase,227 );228 const connectionId = String(connection.id);229 await setWebhookSecret(connectionId);230231 const harness = await createInboundAppHarness();232 try {233 testServer.use(234 createLinearQueryOverride('IssueById', async ({ variables }) => {235 return HttpResponse.json({236 data: {237 issue: createLinearIssue({238 id: (variables.id as string) ?? 'linear-issue-1',239 title: 'Expected title',240 }),241 },242 });243 }),244 );245246 const payload = createLinearWebhookPayload(247 'Issue',248 'create',249 createLinearIssue({ id: 'linear-issue-1', title: 'Expected title' }),250 );251252 const response = await postLinearWebhook({253 app: harness.app,254 accountId: actor.accountId,255 connectionId,256 payload,257 deliveryId: `delivery-${randomUUID()}`,258 });259260 expect(response.status).toBe(200);261262 await processWebhookAndInboundJobs({263 moduleRef: harness.moduleRef,264 webhookQueue: harness.webhookQueue,265 inboundQueue: harness.inboundQueue,266 });267268 // Assert domain row269 const { data: rows } = await supabase270 .from('tasks')271 .select('id,title,status')272 .eq('account_id', actor.accountId)273 .eq('title', 'Expected title')274 .limit(1);275276 expect(rows).toHaveLength(1);277278 // Assert mapping279 const { data: mapping } = await supabase280 .from('sync_entity_mappings')281 .select('external_entity_type,external_id,hamster_entity_type,hamster_id')282 .eq('sync_connection_id', connectionId)283 .eq('external_id', 'linear-issue-1')284 .single();285286 expect(mapping?.hamster_entity_type).toBe('task');287 expect(mapping?.hamster_id).toBe(rows?.[0]?.id);288289 // Assert sync log290 const logs = await querySyncLogs(291 connectionId,292 { direction: 'inbound', entityType: 'issue' },293 supabase,294 );295296 expect(297 logs.filter((l) => l.operation === 'create' && l.status === 'success'),298 ).toHaveLength(1);299 } finally {300 await harness.cleanup();301 }302 });303});304```305306### Skeleton conventions307308- **Vault mock with `vi.hoisted`**: every bidirectional spec needs this. For outbound/reconciliation specs, mock with `serializeStoredProviderCredentials({access_token: ...})` instead of `TEST_WEBHOOK_SECRET`.309- **`linearProviderConfig`**: canonical Linear config from `bidirectional-integration-helpers.ts`. Use it so status mapping, team ID, and workspace config match what MSW base handlers expect.310- **Actor tracking**: push every actor to `actorsForCleanup` and add the account ID to `accountIdsForSyncCleanup` immediately after creation.311- **`try / finally` around harness**: always clean up even if the test throws — leaked Redis connections cause "Connection is closed" errors in subsequent tests.312- **`String(connection.id)`**: connection IDs from Supabase are typed `string | number`. Cast once at the top.313314## Full-runtime harnesses vs focused worker specs315316- **Full-runtime sync specs** boot `SyncEngineModule`, use real Supabase + Redis, and often use MSW at the Linear boundary. These are the `bidirectional-*.integration.spec.ts`, `outbound-operational`, `reconciliation-operational`, and `sync-connections.controller` specs.317- **Focused worker/service integration specs** exercise one worker or service with real queue/storage seams but without the full shared app harness. These are `outbound-event-worker.integration.spec.ts`, `outbox-worker.integration.spec.ts`, etc.318319Use the focused specs when the behavior under test is primarily about outbox claiming, lease handling, dedupe, or deterministic job construction. Do not force those cases into the larger operational canary shape.320321## Loop suppression and sync markers322323This repo uses `sync_entity_mappings.last_sync_origin` and `last_sync_applied_at` to suppress immediate echo loops. When testing follow-up inbound or outbound behavior:324325- prefer directly nulling or backdating those fields in test setup326- avoid `sleep` or arbitrary timeouts to wait out the suppression window327328```typescript329// Deactivate suppression for a follow-up inbound update test330await supabase331 .from('sync_entity_mappings')332 .update({ last_sync_origin: null, last_sync_applied_at: null })333 .eq('sync_connection_id', connectionId)334 .eq('external_id', 'linear-issue-1');335```336337`NULL` values in both fields bypass the check entirely.338339## MSW and Fixtures340341See `apps/sync/TESTING.md` for the full MSW setup reference, fixture factory list, and error helper catalog.342343Key decision rules:344345- Add to `linearBaseHandlers` when the same Linear operation will be used across several tests.346- Use `createLinearQueryOverride` or `createLinearMutationOverride` when the behavior is specific to one test.347- Base handlers intentionally validate minimal required inputs (e.g. `IssueCreate` rejects missing `title` or `teamId`). Do not weaken them to make a test pass — override the operation instead.348- Service-level integration tests use MSW. Lower-level adapter or service unit specs use direct `vi.stubGlobal('fetch', ...)`. Default to MSW + harness for sync integration tests.349350## Assertions That Matter351352Prefer these repo-native assertions over shallow status checks:353354- domain row updated in the correct table355- mapping row exists and points to the expected `hamster_id` / `external_id`356- `sync_logs` contains the expected `direction`, `entity_type`, `operation`, and `status`357- `sync_outbound_events.processed_at` changed when testing outbound completion358- relevant queue received the right job name when testing HTTP flows359360For initiative-related sync, remember that `initiative_briefs` is the canonical relationship set. When a change affects initiative/project linkage, assert the canonical link rows instead of treating `brief.initiative_id` as the primary contract.361362## Anti-Patterns363364- Do **not** mock Supabase or Redis in sync integration tests.365- Do **not** put new sync integration tests outside `apps/sync/src/**/*.integration.spec.ts`.366- Do **not** use arbitrary sleeps for queue or suppression timing.367- Do **not** reuse a queue after cleanup; create fresh queues in `beforeEach`.368- Do **not** bypass unexpected Linear requests with `'bypass'` unless the test explicitly needs it.369- Do **not** assert only the local entity row when mappings or sync logs are the real contract.370- Do **not** forget `clearOutboundEvents(...)` before asserting update/delete outbox events for an entity that was just inserted.371- Do **not** pass `accountId` where a real auth user ID is required (for example `initiatives.owner_id` references `auth.users.id`).372- Do **not** forget `vi.unstubAllEnvs()` in afterEach — env stubs leak across tests without it.373- Do **not** skip the vault credentials mock — the sync engine calls `getConnectionProviderCredentials` to resolve both webhook secrets and provider tokens.374- Do **not** forget `try / finally` around harness usage — leaked Redis connections cause "Connection is closed" errors in subsequent tests.375376## Verification377378Run the smallest useful test first:379380```bash381pnpm --filter sync exec vitest run --config vitest.config.integration.ts \382 apps/sync/src/modules/sync-engine/<path-to-spec>.integration.spec.ts383```384385Then run the full integration suite when the change affects shared helpers, MSW setup, queue wiring, or multiple spec families:386387```bash388pnpm --filter sync test:integration389```390391If runtime code changed alongside tests, also run:392393```bash394pnpm --filter sync typecheck395```396397If the change touches shared helpers, queue wiring, or sync runtime code beyond a narrow test-only edit, also run:398399```bash400pnpm --filter sync build401```