# 调试与测试

> 开发者模式、构建与重新加载、日志、常见的加载错误，以及用 nsh test 做单元测试。

- 网页：https://dinox.info/guides/atomd-plugins/debugging
- 本页 Markdown：https://dinox.info/guides/atomd-plugins/debugging.md
- 全部文档索引：https://dinox.info/llms.txt

## 开发循环

1. 打开 **Settings → Plugins → Developer mode**。

2. 构建到笔记库的插件目录：

   ```bash
   DEST="/path/to/vault/.atomd/plugins/word-count"
   nsh build . -o "$DEST" && cp manifest.json "$DEST/"
   ```

3. 在 **Settings → Plugins** 点 **Reload**。atomd 会重新扫描插件目录，重启所有启用的插件。

可以把第 2 步写成 `package.json` 脚本或 `Makefile`，每次保存后运行。

> **提示**
> 开发构建是未签名的，只在 Developer mode 打开时加载。关掉 Developer mode 后，它们仍然出现在列表里，但不能启用。

## 看日志

插件里的 `console.log`、`console.warn`、`console.error` 都写到 atomd 的日志。从终端启动 atomd 就能看到：

```bash
RUST_LOG=info /Applications/atomd.app/Contents/MacOS/atomd
```

插件启动失败、超出资源限制、调用被拒绝时，**Settings → Plugins** 里的插件状态会显示原因。

## 常见的加载问题

插件没有出现在列表里时，**Settings → Plugins** 底部会列出原因：

| 提示                                       | 处理                                                                           |
| ---------------------------------------- | ---------------------------------------------------------------------------- |
| `needs plugin API 2, atomd serves 1`     | `manifest.json` 的 `api` 写错了，或者需要更新 atomd                                     |
| `needs atomd X or later`                 | 当前 atomd 版本低于 `minAtomdVersion`                                              |
| `no bundle.js (build it with nsh build)` | 文件夹里只有 `manifest.json`，忘了构建                                                  |
| id 不一致                                   | 文件夹名、`manifest.json` 的 `id`、`nsh.json` 的 `id`（`dev.atomd.plugin.<id>`）三者要对得上 |
| version 不一致                              | `manifest.json` 和 `nsh.json` 的 `version` 要相同                                 |
| `Unsigned plugin`                        | 打开 Developer mode                                                            |

调用失败时，检查 `nsh.json` 里有没有声明对应的名称，改完后要重新构建：权限是在构建时写进 `capabilities.json` 的。

## 单元测试

`nsh test` 会运行目录里的 `*.test.ts(x)` 文件，不需要启动 atomd。把业务逻辑（比如字数统计）写成纯函数单独测试最省事：

```ts title="stats.test.ts"
import { expect, test } from "nsh/test";
import { stats } from "./stats";

test("counts Chinese and English words", () => {
  expect(stats("你好 world").words).toBe(3);
});
```

```bash
nsh test .
```

和 atomd 交互的部分（`host.call`、事件）在 atomd 里用 Developer mode 手动验证。