How to test an app
This guide shows you how to test the handler of an app without a Picked API. The tests send the app the signed requests that Picked sends, and a test Picked API answers the calls that the app makes.
You need an app server that uses createAppHandler from @picked/app-kit/server. The
examples use Vitest. Install it in the app directory:
npm install --save-dev vitest1. Build the handler from a function
Put the handler in a function that takes the keys and the fetch of Picked as options.
The server gives it the real values, and a test gives it test values.
src/app.ts:
import { createAppHandler, installationClientFor, type PublicKeySet } from '@picked/app-kit/server'
export interface LeadScoreOptions {
privateKey: string
pickedKeys: PublicKeySet
pickedFetch?: typeof fetch
}
function scoreLead(email: string, company: string): { score: number; tier: string } {
const domain = email.split('@')[1]?.toLowerCase() ?? ''
let score = 20
if (domain !== '' && domain !== 'gmail.com') score += 40
if (company.trim() !== '') score += 20
const tier = score >= 70 ? 'hot' : score >= 40 ? 'warm' : 'cold'
return { score, tier }
}
export function createLeadScoreApp(options: LeadScoreOptions) {
return createAppHandler({
pickedKeys: options.pickedKeys,
tools: {
async score_lead(call) {
const email = typeof call.arguments.email === 'string' ? call.arguments.email : ''
const company = typeof call.arguments.company === 'string' ? call.arguments.company : ''
if (!call.run.test) {
const client = installationClientFor(call, {
privateKey: options.privateKey,
...(options.pickedFetch === undefined ? {} : { fetch: options.pickedFetch }),
})
await client.labels.set([
{ namespace: 'lead-score', key: 'calls', type: 'number', increment: 1 },
])
}
return scoreLead(email, company)
},
},
})
}src/server.ts gives the function the real environment:
import { readAppEnvironment } from '@picked/app-kit/server'
import { serve } from '@picked/app-kit/node'
import { createLeadScoreApp } from './app'
const port = '4103'
const { privateKey, pickedKeys } = readAppEnvironment(process.env, port)
serve(createLeadScoreApp({ privateKey, pickedKeys }), Number(port))2. Make a test Picked API
createFakePicked from @picked/app-kit/testing makes a test Picked API that accepts the
key of the app. Give the handler the public keys and the fetch of the test API:
import { generateKeyPair } from '@picked/app-kit'
import { createFakePicked } from '@picked/app-kit/testing'
import { createLeadScoreApp } from './app'
async function setup() {
const { privateKey } = await generateKeyPair()
const picked = await createFakePicked({ appPrivateKey: privateKey })
const ref = await picked.installationRef('appi_1')
const handle = createLeadScoreApp({
privateKey,
pickedKeys: picked.pickedKeys,
pickedFetch: picked.fetch,
})
return { privateKey, picked, ref, handle }
}picked.installationRef('appi_1') names an installation, as a request from Picked does.
It holds a fresh token. By default the organization is org, the project is proj_1, and
the API origin is https://api.picked.test.
The test API does these things:
- It signs the requests that you build with it, with a Picked key that only the test API holds.
- It answers the label operations of the installation client, and keeps the labels.
- It gives a token to a token request that the private key of the app signs. The request
must also have a session token from the test API, or the test API must have
offlineAccess: true. - It records each GraphQL operation that it gets in
picked.received.
Refer to @picked/app-kit for each member of the test API.
3. Send a signed tool call
toolCall builds the body of a tool call. picked.signedRequest signs it as Picked does.
The handler is a function from a Request to a Response, so the test calls it directly:
import { toolCall } from '@picked/app-kit/testing'
import { describe, expect, it } from 'vitest'
describe('score_lead', () => {
it('scores a lead and counts the call', async () => {
const { picked, ref, handle } = await setup()
const response = await handle(
await picked.signedRequest(
'https://lead-score.test/tools/score_lead',
toolCall(ref, 'score_lead', { email: 'ada@acme.com', company: 'Acme' }),
),
)
expect(response.status).toBe(200)
await expect(response.json()).resolves.toEqual({ output: { score: 80, tier: 'hot' } })
})
})The handler answers these statuses to a tool call:
| Status | Body | When |
|---|---|---|
200 | { "output": { … } } | The tool returns. |
422 | { "error": { "message": "…" } } | The tool throws. The message is the error message. |
404 | { "error": { "message": "Unknown tool <name>" } } | The handler has no tool with that name. |
401 | { "error": "invalid_signature" } | A key that is not a key of Picked signed the request. |
4. Make sure of the labels and the operations
The test API keeps the labels of each installation in picked.labels, by installation ID and
then by <namespace>.<key>. Add these lines to the test:
expect(picked.labels.get('appi_1')?.get('lead-score.calls')).toMatchObject({
type: 'number',
value: '1',
secret: false,
})
expect(picked.received.map((operation) => operation.operationName)).toEqual([
'AppInstallationLabelsSet',
])Each entry of picked.received has the operationName and the variables of the
operation. The client sends these operations:
| Operation | Sent by |
|---|---|
AppInstallationLabels | client.labels.list and client.labels.get |
AppInstallationLabelsSet | client.labels.set |
AppInstallationLabelsDelete | client.labels.delete |
AppInstallationTokenCreate | The client, when it has no token that is valid for a minute or more |
Here the request carried a token, so the client sent no AppInstallationTokenCreate.
5. Test a test run
A workflow test run sets run.test to true on each tool call. Give true as the last
argument of toolCall:
it('counts nothing in a test run', async () => {
const { picked, ref, handle } = await setup()
const response = await handle(
await picked.signedRequest(
'https://lead-score.test/tools/score_lead',
toolCall(ref, 'score_lead', { email: 'ada@acme.com' }, true),
),
)
await expect(response.json()).resolves.toEqual({ output: { score: 60, tier: 'warm' } })
expect(picked.received).toEqual([])
})The call then has the run ID test_wrun.
6. Send lifecycle events and app events
Sign the body of the event, and send it to /lifecycle or to /events:
const installed = await handle(
await picked.signedRequest('https://lead-score.test/lifecycle', {
type: 'installation.created',
...ref,
scopes: [],
}),
)
expect(installed.status).toBe(200)
const published = await handle(
await picked.signedRequest('https://lead-score.test/events', {
type: 'workspace.published',
...ref,
eventId: 'evt_1',
workspaceId: 'wsp_1',
workspaceVersionId: 'wspv_1',
occurredAt: '2026-10-21T00:00:00.000Z',
}),
)
expect(published.status).toBe(200)The handler answers { "ok": true } after onInstall, onUpgrade, onUninstall or
onEvent returns. The other lifecycle types are installation.upgraded and
installation.deleted. Refer to App protocol for the body of
each one.
7. Send a request from a page
A page of the app sends its session token to the server of the app. The function
picked.sessionRequest builds that request, with a session token that the test API signs.
A session token from Picked has no installation token. Remove token and tokenExpiresAt
from the installation that you give to sessionRequest, so that the test session is the
same:
import { installationClientFor, readSession, sessionTokenOf } from '@picked/app-kit/server'
it('reads the labels for a page', async () => {
const { privateKey, picked, ref } = await setup()
const { token, tokenExpiresAt, ...pageRef } = ref
const request = await picked.sessionRequest({
ref: pageRef,
url: 'https://lead-score.test/api/calls',
})
const session = await readSession(request, picked.pickedKeys)
expect(session?.userId).toBe('user-test')
if (session === null) return
const client = installationClientFor(session, {
privateKey,
sessionToken: sessionTokenOf(request),
fetch: picked.fetch,
})
await client.labels.list()
expect(picked.received.map((operation) => operation.operationName)).toEqual([
'AppInstallationTokenCreate',
'AppInstallationLabels',
])
})The session has no token, so the client gets one with AppInstallationTokenCreate. The
test API gives the token without offlineAccess, because the session token comes with
the request. In your app, put the lines that read the session in the route that serves
the page, and give the request to handle.
8. Test an app that works on its own
An app that declares offlineAccess gets tokens with no request from Picked and no
session token. Make the test API with offlineAccess: true:
const picked = await createFakePicked({ appPrivateKey: privateKey, offlineAccess: true })Without it, the test API refuses such a token. Picked gives the same message:
The installation has no offline access; use the token Picked sends with each request
9. Send an MCP request
picked.mcpRequest builds an MCP request as Picked forwards it from the dashboard. It
signs the request for one installation:
const response = await handle(
await picked.mcpRequest('https://lead-score.test/mcp', ref, {
jsonrpc: '2.0',
id: 1,
method: 'tools/list',
}),
)The handler gives the request and the installation to mcp.handle.
10. Make Picked refuse a write
To test what the app does when Picked refuses a label, put a function between the app
and the fetch of the test API. This one refuses each label write with the user error that Picked gives for a value of the wrong type:
const refusing: typeof fetch = async (input, init) =>
typeof init?.body === 'string' && init.body.includes('AppInstallationLabelsSet')
? Response.json({
data: {
labelsSet: {
labels: [],
skipped: [],
userErrors: [
{
field: ['labels', '0', 'value'],
message: 'Value cannot be read as NUMBER.',
code: 'VALUE_INVALID_FOR_TYPE',
},
],
},
},
})
: picked.fetch(input, init)Give refusing to the app as pickedFetch. client.labels.set then throws a
LabelWriteError. The handler answers 422 with the message
labels.0.value: Value cannot be read as NUMBER..
The test API answers only the label operations and AppInstallationTokenCreate. Use the same
method to answer a different GraphQL operation that your app sends.
11. Run the tests
npx vitest runRelated
@picked/app-kit—createFakePicked,toolCalland the installation client.- App protocol — the requests that Picked sends, and how it signs them.
- How to store data for an installation — labels, secret labels and their limits.
- How to add a workflow tool to an app — tool calls and test runs.
