Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions .env.test
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Test-only environment variables.
#
# Loaded by test/integration/globalSetup.ts BEFORE the testcontainer Postgres
# is started. DATABASE_URL is intentionally NOT set here — globalSetup sets it
# dynamically to the container's connection URI.
#
# Everything in this file should be a non-secret stub. No real credentials.

# Copilot
COPILOT_API_KEY=test-copilot-api-key
NEXT_PUBLIC_COPILOT_APP_API_KEY=test-copilot-app-key
NEXT_PUBLIC_COPILOT_DASHBOARD_URL=https://test.copilot.local
COPILOT_ENV=test

# Intuit / QuickBooks
INTUIT_CLIENT_ID=test-intuit-client-id
INTUIT_CLIENT_SECRET=test-intuit-client-secret
INTUIT_REDIRECT_URI_PATH=/api/quickbooks/auth/callback
INTUIT_ENVIRONMENT=sandbox
INTUIT_SANDBOX_API_URL=https://sandbox-quickbooks.api.intuit.com
INTUIT_PRODUCTION_API_URL=https://quickbooks.api.intuit.com
INTUIT_API_MINOR_VERSION=75

# Supabase (stubs — tests don't hit Supabase)
NEXT_PUBLIC_SUPABASE_PROJECT_URL=https://test.supabase.local
NEXT_PUBLIC_SUPABASE_ANON_KEY=test-anon-key

# Cron
CRON_SECRET=test-cron-secret

# Vercel / Next
VERCEL_URL=localhost:3000
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,7 @@ yarn-error.log*
*.tsbuildinfo
next-env.d.ts

.trigger
.trigger

# local decision notes (not published)
/docs
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
"@ngrok/ngrok": "^1.4.1",
"@sentry/esbuild-plugin": "^4.6.1",
"@tailwindcss/postcss": "^4.1.5",
"@testcontainers/postgresql": "^11.14.0",
"@trigger.dev/build": "4.4.4",
"@types/deep-equal": "^1.0.4",
"@types/html-to-text": "^9",
Expand All @@ -80,6 +81,7 @@
"eslint-plugin-prettier": "^5.2.6",
"husky": "^9.1.7",
"lint-staged": "^15.5.1",
"next-test-api-route-handler": "^5.0.4",
"postcss": "^8.5.3",
"prettier": "^3.5.3",
"tailwindcss": "^4.1.5",
Expand Down
7 changes: 6 additions & 1 deletion src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@
import { EnvironmentType } from 'intuit-oauth'
import dotenv from 'dotenv'

dotenv.config()
// Skip loading .env under Vitest so test runs can't silently inherit developer
// creds from the local .env file. Test envs are loaded explicitly by
// test/integration/globalSetup.ts from .env.test.
if (process.env.NODE_ENV !== 'test') {
dotenv.config()
}

export const copilotDashboardUrl =
process.env.NEXT_PUBLIC_COPILOT_DASHBOARD_URL || ''
Expand Down
17 changes: 17 additions & 0 deletions test/fixtures/priceCreated.webhook.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"eventType": "price.created",
"created": "2024-09-11T13:59:58.845233992Z",
"object": "price",
"data": {
"id": "C-wch-eSg",
"createdAt": "2024-09-11T13:59:58.845233992Z",
"object": "price",
"amount": 60000,
"currency": "usd",
"interval": "month",
"intervalCount": 3,
"productId": "2cf93cf0-45fa-485f-b584-03c2c38a3999",
"type": "recurring",
"updatedAt": "2024-09-11T13:59:58.845233992Z"
}
}
118 changes: 118 additions & 0 deletions test/helpers/mocks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import { vi, type Mock } from 'vitest'
import { CopilotAPI } from '@/utils/copilotAPI'
import IntuitAPI from '@/utils/intuitAPI'
import {
TEST_INCOME_ACCOUNT_REF,
TEST_INTERNAL_USER_ID,
TEST_PORTAL_ID,
} from './seed'

// Restricts override keys to the actual method names of the underlying class
// so typos produce a compile-time error. The Mock value type intentionally
// stays loose — tests routinely return shapes that don't match the real
// Promise return type.
type MockMethodOverrides<T> = {
[K in keyof T as T[K] extends (...args: never[]) => unknown
? K
: never]?: Mock
}

type CopilotAPIOverrides = MockMethodOverrides<CopilotAPI>
type IntuitAPIOverrides = MockMethodOverrides<IntuitAPI>

/**
* Factory for a mocked CopilotAPI instance.
*
* Tests mock the CopilotAPI module with `vi.mock('@/utils/copilotAPI')`, then
* wire each `new CopilotAPI(token)` call to an object produced by this factory.
* Override any method via the `overrides` arg to tailor behavior per test.
*/
export function createMockCopilotAPI(overrides: CopilotAPIOverrides = {}) {
return {
getTokenPayload: vi.fn().mockResolvedValue({
workspaceId: TEST_PORTAL_ID,
internalUserId: TEST_INTERNAL_USER_ID,
}),
getProduct: vi.fn().mockResolvedValue({
id: '2cf93cf0-45fa-485f-b584-03c2c38a3999',
name: 'Test Product',
description: 'Test product description',
status: 'active',
createdAt: '2024-09-11T13:59:58.845233992Z',
updatedAt: '2024-09-11T13:59:58.845233992Z',
}),
...overrides,
}
}

/**
* Factory for a mocked IntuitAPI instance.
*
* Defaults represent the happy path for `price.created`:
* - getAnItem returns undefined (no existing item in QB)
* - getAnAccount returns an active income account matching the seeded ref
* - createItem returns a freshly-created QB item
*/
export function createMockIntuitAPI(overrides: IntuitAPIOverrides = {}) {
return {
getAnItem: vi.fn().mockResolvedValue(undefined),
getAnAccount: vi.fn().mockResolvedValue({
Id: TEST_INCOME_ACCOUNT_REF,
Name: 'Sales of Product Income',
SyncToken: '0',
Active: true,
AccountType: 'Income',
}),
createItem: vi.fn().mockResolvedValue({
Id: '999',
Name: 'Test Product',
SyncToken: '0',
UnitPrice: 600,
}),
...overrides,
}
}

export type MockCopilotAPI = ReturnType<typeof createMockCopilotAPI>
export type MockIntuitAPI = ReturnType<typeof createMockIntuitAPI>

/**
* Wires the module-mocked CopilotAPI + IntuitAPI to return shared instances
* for the duration of a test. Pass pre-built instances (e.g., with overrides)
* or accept the defaults.
*
* Returns the instances so tests can assert on call counts / arguments.
*
* Must use `function` (not arrow) so the mock is callable with `new`.
*
* CAVEAT — shared instance across multiple `new` sites:
* The price.created flow constructs `new CopilotAPI(...)` TWICE per request —
* once in `authenticate()` (calls `.getTokenPayload()`) and once in
* `webhookPriceCreated` (calls `.getProduct()`). Both sites receive the SAME
* `copilot` mock object returned here. This is fine when asserting on
* different methods (e.g., `getProduct` only fires from the service call),
* but be careful with shared methods: `toHaveBeenCalledTimes(1)` on a method
* both sites touch would reflect the sum of both call sites. Same applies to
* IntuitAPI if/when it gets instantiated more than once per request.
*/
export function installMockApis(
opts: {
copilot?: MockCopilotAPI
intuit?: MockIntuitAPI
} = {},
): { copilot: MockCopilotAPI; intuit: MockIntuitAPI } {
const copilot = opts.copilot ?? createMockCopilotAPI()
const intuit = opts.intuit ?? createMockIntuitAPI()

vi.mocked(CopilotAPI).mockImplementation(function (
this: unknown,
): CopilotAPI {
return copilot as unknown as CopilotAPI
} as unknown as typeof CopilotAPI)

vi.mocked(IntuitAPI).mockImplementation(function (this: unknown): IntuitAPI {
return intuit as unknown as IntuitAPI
} as unknown as typeof IntuitAPI)

return { copilot, intuit }
}
46 changes: 46 additions & 0 deletions test/helpers/priceCreatedTestSetup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { beforeEach, afterEach, vi } from 'vitest'
import { truncateAllTestTables } from '@test/helpers/testDb'
import {
installMockApis,
type MockCopilotAPI,
type MockIntuitAPI,
} from '@test/helpers/mocks'

type InstallOpts = Parameters<typeof installMockApis>[0]

export interface PriceCreatedTestHandle {
copilot: MockCopilotAPI
intuit: MockIntuitAPI
}

/**
* Registers the standard `beforeEach` (truncate + installMockApis) and
* `afterEach` (clearAllMocks) hooks used by every price.created integration
* test. Returns a live handle whose `copilot` / `intuit` properties are
* replaced with fresh mock instances before each test.
*
* The `optsFactory` is invoked once per test so callers can supply overrides
* whose underlying `vi.fn()`s are freshly instantiated — a static opts object
* would be broken by the `vi.clearAllMocks()` call in afterEach.
*/
export function setupPriceCreatedTest(
optsFactory?: () => InstallOpts,
): PriceCreatedTestHandle {
const handle = {} as PriceCreatedTestHandle

beforeEach(async () => {
await truncateAllTestTables()
const { copilot, intuit } = installMockApis(optsFactory?.())
handle.copilot = copilot
handle.intuit = intuit
})

afterEach(() => {
// clearAllMocks (not restoreAllMocks) — the module-level mock factories in
// test/integration/setup.ts must stay installed across tests; we only want
// to reset call counts and implementations set in beforeEach.
vi.clearAllMocks()
})

return handle
}
103 changes: 103 additions & 0 deletions test/helpers/seed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import type { InferInsertModel } from 'drizzle-orm'
import type { z } from 'zod'
import { db } from '@/db'
import {
QBPortalConnection,
QBPortalConnectionCreateSchema,
} from '@/db/schema/qbPortalConnections'
import { QBProductSync } from '@/db/schema/qbProductSync'
import { QBSetting, QBSettingCreateSchema } from '@/db/schema/qbSettings'

export const TEST_PORTAL_ID = 'test-portal-00000001'
export const TEST_REALM_ID = 'test-realm-123'
export const TEST_ACCESS_TOKEN = 'test-access-token'
export const TEST_REFRESH_TOKEN = 'test-refresh-token'
export const TEST_INCOME_ACCOUNT_REF = '100'
export const TEST_ASSET_ACCOUNT_REF = '101'
export const TEST_EXPENSE_ACCOUNT_REF = '102'
export const TEST_INTERNAL_USER_ID = 'test-internal-user-id'
export const TEST_WEBHOOK_TOKEN = 'test-token-xyz'

// Override types are derived from the Drizzle-generated insert schemas so
// they stay in sync with the DB schema automatically. Using `Partial<typeof base>`
// would widen primitives (e.g., `true` → `boolean`) but wouldn't track column
// type changes in the underlying schema.
type PortalOverrides = Partial<z.infer<typeof QBPortalConnectionCreateSchema>>
type SettingOverrides = Partial<z.infer<typeof QBSettingCreateSchema>>
type ProductSyncOverrides = Partial<InferInsertModel<typeof QBProductSync>>

const basePortalConnection: z.infer<typeof QBPortalConnectionCreateSchema> = {
portalId: TEST_PORTAL_ID,
intuitRealmId: TEST_REALM_ID,
accessToken: TEST_ACCESS_TOKEN,
refreshToken: TEST_REFRESH_TOKEN,
// Keeps `isTokenFresh` true so tests don't trigger a real Intuit OAuth call.
tokenSetTime: new Date(),
expiresIn: 3600,
XRefreshTokenExpiresIn: 8_726_400,
intiatedBy: TEST_INTERNAL_USER_ID,
incomeAccountRef: TEST_INCOME_ACCOUNT_REF,
assetAccountRef: TEST_ASSET_ACCOUNT_REF,
expenseAccountRef: TEST_EXPENSE_ACCOUNT_REF,
}

const baseSetting: z.infer<typeof QBSettingCreateSchema> = {
portalId: TEST_PORTAL_ID,
absorbedFeeFlag: false,
useCompanyNameFlag: false,
createNewProductFlag: true,
initialInvoiceSettingMap: true,
initialProductSettingMap: true,
syncFlag: true,
isEnabled: true,
}

export async function seedPortalConnection(overrides: PortalOverrides = {}) {
const [row] = await db
.insert(QBPortalConnection)
.values({ ...basePortalConnection, ...overrides })
.returning()
return row
}

export async function seedSetting(overrides: SettingOverrides = {}) {
const [row] = await db
.insert(QBSetting)
.values({ ...baseSetting, ...overrides })
.returning()
return row
}

const baseProductSync: InferInsertModel<typeof QBProductSync> = {
portalId: TEST_PORTAL_ID,
productId: '2cf93cf0-45fa-485f-b584-03c2c38a3999',
priceId: 'C-wch-eSg',
name: 'Test Product',
copilotName: 'Test Product',
unitPrice: '60000.00',
qbItemId: '999',
qbSyncToken: '0',
}

export async function seedProductSync(overrides: ProductSyncOverrides = {}) {
const [row] = await db
.insert(QBProductSync)
.values({ ...baseProductSync, ...overrides })
.returning()
return row
}

/**
* Convenience seeder for the common "healthy portal" fixture used by
* most tests. Returns both rows for assertions if needed.
*/
export async function seedHealthyPortal(
opts: {
portal?: PortalOverrides
setting?: SettingOverrides
} = {},
) {
const portal = await seedPortalConnection(opts.portal)
const setting = await seedSetting(opts.setting)
return { portal, setting }
}
26 changes: 26 additions & 0 deletions test/helpers/testDb.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { sql } from 'drizzle-orm'
import { db } from '@/db'

/**
* Wipes every table in the schema that integration tests can touch. Call in
* `beforeEach` — the testcontainer Postgres is shared across the full
* integration run, so cross-test contamination is a real risk.
*
* If a new table is added to `src/db/schema/*.ts`, add it here too. The
* consequence of forgetting is silent cross-test contamination — tests pass
* in isolation but fail in full-suite runs depending on file order.
*/
export async function truncateAllTestTables() {
await db.execute(sql`
TRUNCATE TABLE
qb_sync_logs,
qb_connection_logs,
qb_customers,
qb_invoice_sync,
qb_payment_sync,
qb_product_sync,
qb_settings,
qb_portal_connections
RESTART IDENTITY CASCADE
`)
Comment thread
SandipBajracharya marked this conversation as resolved.
}
Loading
Loading