Files
oqyude 07d4bddc64 test(main): покрытие жизненного цикла плагина; loadSettings не теряет дефолты модуля
Симптом (ревью 2026-11-29, §7): `src/main.ts` — единственный файл в src/,
которого нет в tests/, а именно он держит порядок onload/onunload и слияние
DEFAULT_SETTINGS с сохранёнными данными.

Что нашлось, когда тест появился: `loadSettings` делал
`Object.assign({}, DEFAULT_SETTINGS, saved)`. У shallow-копии `modules` — та
же ссылка, что у DEFAULT_SETTINGS, поэтому:
- заполнение пропущенного модуля правило сам DEFAULT_SETTINGS, и следующий
  экземпляр плагина (или следующий тест) получал чужие настройки;
- сохранённая запись вида `{enabled:false}` без поля `settings` обнуляла
  дефолты модуля: getModuleSettings возвращал {} вместо extensions/processEmbeds.

Правка: слияние по модулям — `enabled` из сохранённого (иначе true),
`settings` = дефолты модуля поверх сохранённых значений. DEFAULT_SETTINGS
больше не мутируется.

Тест tests/main.test.ts, 8 кейсов: дефолты при пустом состоянии; сохранённые
значения поверх дефолтов; запись без settings восстанавливает дефолты; второй
экземпляр не видит чужих настроек; onload грузит только включённые модули и
регистрирует вкладку; loadModule идемпотентен, unloadModule игнорирует
незагруженный модуль; onunload выгружает всё ровно один раз; saveSettings
пишет текущий объект. Мок obsidian дополнен App/PluginSettingTab — без них
модуль не импортируется в тесте.

Проверено: vitest run — 4 файла, 33/33 (было 25); tsc --noEmit — чисто;
eslint src/ — 0 errors, 2 warnings (те же, что до правки); prettier --check
src/ tests/ — чисто; npm run build — ok, main.js 17.2 kb.
2026-12-03 14:19:00 +03:00

173 lines
5.8 KiB
TypeScript

import { describe, it, expect, vi, afterEach } from 'vitest';
import ZeroQoLModulesPlugin from '../src/main';
import { MODULES } from '../src/modules';
import { DEFAULT_SETTINGS } from '../src/settings';
// `src/main.ts` is the one file in src/ with no tests (ревью 2026-11-29, §7):
// it owns the onload/onunload order and the merge of DEFAULT_SETTINGS with
// saved data — the place where a mistake shows up as «модуль включён, но не
// работает» or «настройки слетели». These tests pin that contract.
// The Obsidian `Plugin` mock in __mocks__/obsidian.ts has no loadData /
// saveData / addSettingTab: the real base class provides them, the mock does
// not. So each test hands the plugin the three methods it uses.
type Harness = ZeroQoLModulesPlugin & {
loadData: () => Promise<unknown>;
saveData: (data: unknown) => Promise<void>;
addSettingTab: (tab: unknown) => void;
};
function makeApp() {
// Modules subscribe in onload: workspace for editor events, vault for rename.
return {
workspace: { on: vi.fn(() => ({})), offref: vi.fn() },
vault: { on: vi.fn(() => ({})), offref: vi.fn() },
};
}
function makePlugin(saved: unknown = null): Harness {
// The real Plugin base class takes (app, manifest); the test mock is a bare
// class, and the plugin's own constructor is implicit. So construct it as a
// zero-arg class and hand it the two methods it actually calls.
const Ctor = ZeroQoLModulesPlugin as unknown as new () => ZeroQoLModulesPlugin;
const plugin = new Ctor() as Harness;
(plugin as unknown as { app: unknown }).app = makeApp();
plugin.loadData = vi.fn(async () => saved);
plugin.saveData = vi.fn(async () => undefined);
plugin.addSettingTab = vi.fn();
return plugin;
}
function moduleCfg(plugin: ZeroQoLModulesPlugin, id: string) {
return plugin.settings.modules[id];
}
afterEach(() => {
vi.restoreAllMocks();
});
describe('ZeroQoLModulesPlugin.loadSettings', () => {
it('fills every registered module with defaults when nothing is saved', async () => {
const plugin = makePlugin(null);
await plugin.loadSettings();
expect(Object.keys(plugin.settings.modules).sort()).toEqual(
MODULES.map((m) => m.id).sort(),
);
for (const module of MODULES) {
const cfg = moduleCfg(plugin, module.id);
expect(cfg.enabled).toBe(true);
expect(cfg.settings).toEqual(module.defaultSettings);
}
});
it('keeps saved values and adds defaults for modules the saved data omits', async () => {
const [first, second] = MODULES;
const plugin = makePlugin({
modules: {
[first.id]: { enabled: false, settings: { custom: 'kept' } },
},
});
await plugin.loadSettings();
expect(moduleCfg(plugin, first.id)).toEqual({
enabled: false,
// saved values sit on top of the module's defaults
settings: { ...first.defaultSettings, custom: 'kept' },
});
expect(moduleCfg(plugin, second.id)).toEqual({
enabled: true,
settings: second.defaultSettings,
});
});
it('restores default keys when saved data has a module without settings', async () => {
const [first] = MODULES;
const plugin = makePlugin({ modules: { [first.id]: { enabled: false } } });
await plugin.loadSettings();
expect(moduleCfg(plugin, first.id).enabled).toBe(false);
expect(moduleCfg(plugin, first.id).settings).toEqual(first.defaultSettings);
});
it('does not mutate DEFAULT_SETTINGS, so a second plugin instance sees clean defaults', async () => {
const [first] = MODULES;
const dirty = makePlugin({
modules: { [first.id]: { enabled: false, settings: { custom: 'leak' } } },
});
await dirty.loadSettings();
const clean = makePlugin(null);
await clean.loadSettings();
expect(moduleCfg(clean, first.id).enabled).toBe(true);
expect(moduleCfg(clean, first.id).settings).toEqual(first.defaultSettings);
expect(DEFAULT_SETTINGS.modules[first.id]).toEqual({
enabled: true,
settings: first.defaultSettings,
});
});
});
describe('ZeroQoLModulesPlugin lifecycle', () => {
it('loads only the modules enabled in settings and registers the settings tab', async () => {
const [on, off] = MODULES;
const onloadOn = vi.spyOn(on, 'onload');
const onloadOff = vi.spyOn(off, 'onload');
const plugin = makePlugin({
modules: {
[on.id]: { enabled: true, settings: on.defaultSettings },
[off.id]: { enabled: false, settings: off.defaultSettings },
},
});
await plugin.onload();
expect(onloadOn).toHaveBeenCalledTimes(1);
expect(onloadOn).toHaveBeenCalledWith(plugin, on.defaultSettings);
expect(onloadOff).not.toHaveBeenCalled();
expect(plugin.addSettingTab).toHaveBeenCalledTimes(1);
});
it('loadModule is idempotent and unloadModule ignores a module that was never loaded', async () => {
const [module] = MODULES;
const onload = vi.spyOn(module, 'onload');
const onunload = vi.spyOn(module, 'onunload');
const plugin = makePlugin(null);
await plugin.loadSettings();
plugin.loadModule(module);
plugin.loadModule(module);
expect(onload).toHaveBeenCalledTimes(1);
plugin.unloadModule(MODULES[1]);
expect(onunload).not.toHaveBeenCalled();
plugin.unloadModule(module);
plugin.unloadModule(module);
expect(onunload).toHaveBeenCalledTimes(1);
});
it('onunload unloads every loaded module once, even if called twice', async () => {
const spies = MODULES.map((m) => vi.spyOn(m, 'onunload'));
const plugin = makePlugin(null);
await plugin.loadSettings();
for (const m of MODULES) plugin.loadModule(m);
plugin.onunload();
plugin.onunload();
for (const spy of spies) expect(spy).toHaveBeenCalledTimes(1);
});
it('saveSettings writes the settings object it holds', async () => {
const plugin = makePlugin(null);
await plugin.loadSettings();
plugin.settings.modules[MODULES[0].id].enabled = false;
await plugin.saveSettings();
expect(plugin.saveData).toHaveBeenCalledWith(plugin.settings);
});
});