# Write Unit Tests for an Obsidian Plugin

Yes. An agent adds Vitest to your Obsidian plugin with a mock of the obsidian module, tests settings and commands, adds npm test to CI, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/write-unit-tests/obsidian-plugin/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the plugin and its toolchain before it adds a test runner, because Obsidian plugins import a package that has no runtime. In a plugin like obsidianmd/obsidian-sample-plugin, `src/main.ts` exports `MyPlugin extends Plugin` whose `onload` calls `loadSettings`, adds a ribbon icon, a status bar item, three commands (`open-modal-simple`, `replace-selected` with an `editorCallback` that calls `editor.replaceSelection('Sample editor command')`, and `open-modal-complex` with a `checkCallback` gated on `getActiveViewOfType(MarkdownView)`), a settings tab, a DOM click listener on `activeDocument` and a five-minute interval. `src/settings.ts` holds `MyPluginSettings`, `DEFAULT_SETTINGS` with `mySetting: 'default'`, and a `SampleSettingTab` whose text field writes back through `saveSettings`. `loadSettings` is `Object.assign({}, DEFAULT_SETTINGS, await this.loadData())`. `package.json` has `dev`, `build` (`tsc -noEmit -skipLibCheck` then esbuild), `version` and `lint` scripts and no `test`; dev dependencies are `esbuild` 0.25.5, `typescript`, `eslint` 9 with `eslint-plugin-obsidianmd`, and `obsidian` at `latest`, which ships only `obsidian.d.ts`. `esbuild.config.mjs` marks `obsidian`, `electron` and the CodeMirror packages external, `tsconfig.json` is `strict` with `noUncheckedIndexedAccess` and includes only `src/**/*.ts`, and `.github/workflows/lint.yml` runs `npm ci`, `npm run build --if-present` and `npm run lint` on three Node versions.

Because `import { Plugin } from 'obsidian'` resolves to types only, any test that loads `main.ts` needs a stand-in. The agent adds `vitest` and writes `tests/mocks/obsidian.ts`: a `Plugin` base class with `addCommand` recording into an array, `loadData` and `saveData` backed by an in-memory object the test can preset, `addRibbonIcon`, `addStatusBarItem` returning an element with `setText`, `addSettingTab`, `registerDomEvent` and `registerInterval` as no-ops that record their arguments, plus `Notice`, `Modal`, `MarkdownView`, `PluginSettingTab` and a chainable `Setting`. `vitest.config.ts` aliases `obsidian` to that file, sets `environment: 'jsdom'` so `window.setInterval` exists, and a setup file defines the `activeDocument` global that `main.ts` uses, which Obsidian normally provides.

The tests in `tests/main.test.ts` and `tests/settings.test.ts` pin what a user would notice: `loadSettings` merges a saved partial object over `DEFAULT_SETTINGS` and falls back to the default when `loadData` returns null; `saveSettings` passes the current object to `saveData`; `onload` registers exactly the three command ids, which must never change once released; `replace-selected` calls `replaceSelection` with the expected string on a fake editor; `open-modal-complex` returns `false` when `getActiveViewOfType` yields nothing and `true` when it yields a view, and opens the modal only when `checking` is `false`; and the settings tab's text field writes a changed value and calls `saveSettings` once.

Wiring follows the repository's conventions. A `test` script, `vitest run`, joins `package.json`; a `tsconfig.test.json` extends the root config to include `tests/` so `tsc -noEmit` in `build` still checks only `src/`; the ESLint `projectService` already covers new TypeScript files, so `npm run lint` picks the tests up without a new config block; and `lint.yml` gains an `npm test` step after lint on the same Node matrix. The agent runs `npm ci`, `npm run build`, `npm run lint` and `npm test` in its sandbox and includes the output. `release.yml`, `manifest.json` and `versions.json` are untouched.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add unit tests to this Obsidian plugin. Read src/main.ts, src/settings.ts, package.json, tsconfig.json, esbuild.config.mjs, the ESLint config and the GitHub workflows first. Use Vitest with a jsdom environment and a hand-written mock of the obsidian module aliased in the Vitest config, covering Plugin, Notice, Modal, MarkdownView, PluginSettingTab and Setting, plus the activeDocument global. Test settings loading and merging with defaults, saving, the exact command ids registered in onload, the editor command's replaceSelection call, the checkCallback command in both checking modes and with and without an active markdown view, and the settings tab writing a changed value. Add a test script, a tsconfig for tests that keeps the build's tsc check limited to src, and an npm test step in the lint workflow. Do not change manifest.json, versions.json or the release workflow. Run build, lint and test and include the output. Open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that adds `vitest.config.ts`, `tests/mocks/obsidian.ts`, `tests/setup.ts`, `tests/main.test.ts`, `tests/settings.test.ts` and `tsconfig.test.json`, changes `package.json` and `package-lock.json` (`vitest`, `jsdom`, the `test` script) and adds one step to `.github/workflows/lint.yml`. `src/`, `manifest.json`, `versions.json`, `esbuild.config.mjs` and `release.yml` are unchanged.

The description lists each test with the behaviour it pins, quotes the Vitest summary, the `tsc` and esbuild build output and the ESLint result, and explains what the mock does and does not emulate. The commands and full output are in the transcript at `GET /o/{org}/sessions/{id}/messages`; the updated workflow runs the suite on the pull request.

Before merging, a reviewer reads the mock for anything that hides real Obsidian behaviour, checks the command ids in the tests are the ones already released, and decides whether the mock should move to a shared package if more plugins will use it. A follow-up message to the same session can add tests for a new command.

## Run it on every plugin repository created from the sample template

A team that maintains several Obsidian plugins starts one run per repository with one `POST /o/{org}/sessions` each, the repository in `resources` and this prompt as `input`. Each run reads its own `main.ts` and settings, so a plugin with a view or a file-menu item gets mock entries and tests for those, while the Vitest wiring and workflow step stay the same shape.

Send a `request_id`, a UUID v5 of the repository's full name, so a retried call returns the run it already started. The key's `webhook_url` reports when each run the key starts finishes, with the run's final answer in `result`.

## Why run it on Rush?

Obsidian plugin tests stall on the first import: the `obsidian` package is types only, so nothing runs until a mock of the plugin API exists, and writing that mock is most of the work. The agent reads which parts of the API the plugin actually touches and mocks exactly those, then runs build, lint and the suite in a sandbox of its own with the output kept.

The pull request carries the test list, the mock's scope and the passing output, so the review is a check of what the tests promise rather than a setup session. Several plugins can be covered at once, each in its own sandbox with its own pull request and its own mock.

## Frequently asked questions

### Why mock the obsidian module at all?

The `obsidian` npm package contains type definitions and no JavaScript; the real implementation lives inside the Obsidian app. Any test that imports `main.ts` needs a module that satisfies those types at runtime, so the agent writes one covering the classes this plugin uses and aliases it in the Vitest config.

### Will the build or the release workflow change?

No. The `build` script still runs `tsc -noEmit` over `src/` only, because tests get their own `tsconfig.test.json`, and esbuild still bundles `src/main.ts` to `main.js`. `release.yml`, which builds and drafts a GitHub release on a tag, is untouched; only `lint.yml` gains a test step.

### Can the tests catch a changed command id?

Yes. One test asserts the exact set of ids `onload` registers, because renaming a released command breaks users' hotkeys. If you add a command, the test fails until you add its id, which is the point.

### Does this test the UI?

It tests the logic behind it: what the settings tab writes when its field changes and what the check callback returns. Rendering inside Obsidian itself is not reproduced; the mock's `Setting` records calls instead of drawing. Manual installation into a vault, as the README describes, remains the end-to-end check.

## More Obsidian plugin jobs

- [Add a Custom Code Block Renderer to an Obsidian Plugin](https://getrush.ai/run/add-code-block-processor/obsidian-plugin/)
- [Add Context Menu Items to an Obsidian Plugin](https://getrush.ai/run/add-context-menu/obsidian-plugin/)
- [Add a Custom Sidebar View to an Obsidian Plugin](https://getrush.ai/run/add-custom-view/obsidian-plugin/)

## The same job on other stacks

- [Write Unit Tests for a Payload CMS App](https://getrush.ai/run/write-unit-tests/payload/)
- [Write Unit Tests for a Rust Project](https://getrush.ai/run/write-unit-tests/rust/)
- [Write Rack::Test Tests for a Sinatra Service That Has None](https://getrush.ai/run/write-unit-tests/sinatra/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
