You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jest运行测试报错:无法找到obsidian模块

解决Jest测试Obsidian插件时找不到obsidian模块的问题

问题核心

obsidian npm包仅包含TypeScript类型声明,没有实际运行时代码,Jest在Node环境下无法解析该模块的实现,因此需要通过Mock来模拟Obsidian的API。

解决方案

1. 创建全局Mock文件

在项目根目录下新建__mocks__/obsidian.ts,根据你的测试需求导出需要模拟的类、类型或函数:

// __mocks__/obsidian.ts
// 基础模拟示例,可根据测试场景扩展
export class App {
  vault = {
    getFiles: jest.fn(() => []),
    create: jest.fn(),
  };
}

export class Vault {}
export class TFile {
  constructor(public path: string, public name: string) {}
}

// 按需添加其他需要的API模拟
export type MetadataCache = {
  getFileCache: jest.fn(() => null);
};

2. 配置Jest指向Mock

修改jest.config.ts,添加moduleNameMapper将obsidian模块映射到你的Mock文件:

export default {
  preset: 'ts-jest',
  testEnvironment: 'node',
  moduleNameMapper: {
    '^obsidian$': '<rootDir>/__mocks__/obsidian.ts',
  },
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
};

3. 在测试文件中使用Mock

如果需要针对单个测试用例定制Mock行为,可在测试文件中覆盖全局Mock:

// tests/sync_algorithm.test.ts
import { App, TFile } from 'obsidian';

// 定制当前测试文件的App mock
jest.mock('obsidian', () => ({
  ...jest.requireActual('obsidian'), // 保留类型
  App: jest.fn(() => ({
    vault: {
      getFiles: jest.fn(() => [new TFile('test/note.md', 'note.md')]),
    },
  })),
}));

test('测试同步逻辑', () => {
  const app = new App();
  // 编写你的测试断言
  expect(app.vault.getFiles).toHaveBeenCalled();
});

4. 检查TypeScript配置

确保tsconfig.json的compilerOptions正确配置,避免类型解析错误:

{
  "compilerOptions": {
    "moduleResolution": "node",
    "types": ["jest", "node"],
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true
  },
  "include": ["src/**/*", "tests/**/*", "__mocks__/**/*"]
}

关键注意事项

  • 所有Obsidian API的调用都需要通过Mock模拟,因为不存在运行时实现
  • 如果参考其他插件的配置,注意他们可能已经封装了自定义Mock工具类
  • 确保__mocks__目录在Jest识别的根目录范围内(可通过rootDir配置指定)

内容的提问来源于stack exchange,提问作者LBF38

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 19:20:53