# `npx @sanity/cli functions test`

Invoke a local Function with a test payload. Local execution can still make network requests or mutate external systems, so inspect the handler and payload before running it.

## Run a bounded test

Always provide the Function name. Prefer a JSON file for nontrivial payloads:

```sh
npx @sanity/cli functions test process-order --file payload.json --json
```

Use `--data '{"orderId":"order-123"}'` for a small inline JSON object. `--data`, `--file`, and `--document-id` are alternative input modes, and each must resolve to a JSON object. File paths are joined to the current working directory, so pass relative paths.

Payloads reach document and media-library Functions only. Scheduled and sync-tag-invalidation Functions are invoked with a fixed scheduled event, and any payload flag is accepted and then ignored.

For document and media-library Functions, the event defaults to `create` and also accepts `update` and `delete`. For an update event, provide one complete before/after pair:

```sh
npx @sanity/cli functions test process-order --event update --file-before before.json --file-after after.json --json
```

The Blueprint's `event.filter` and `event.projection` are applied to the payload before the handler runs, and a payload the filter excludes is skipped rather than executed. `--timeout SECONDS` overrides the Function's configured `timeout` for this run (default 10 seconds).

## Remote data and credentials

`--document-id` fetches a document (`--project-id`, `--dataset`) or a media-library asset (`--media-library-id`) with the CLI's stored token before local execution. `--api` sets the API version used for that fetch.

`--with-user-token` injects the authenticated CLI token into the Function context. Use it only for trusted local code when authenticated API behavior is part of the test. Never include the token in payloads or output.

The JSON result contains logs and any Function response. Review logs for sensitive data before sharing them.
