Your Grace, I’ve updated the test to mock the obsidian module using your manual stub and adjusted the assertions to verify createDiv calls for the sections. This ensures the test uses the shared mock and aligns with the implementation. Let me know if you’d like further tweaks.
Your Humble Servant, Sebastien
User
We should be using our MockObsidianElement type not defining a new one right?
@@ -2,8 +2,8 @@
import { createMockObsidianElement } from '../__mocks__/obsidian';
+ import type { MockObsidianElement } from '../__mocks__/obsidian';
import { TagManagementView } from './TagManagementView';
import type { MetadataCache, Vault, WorkspaceLeaf } from 'obsidian';
- import type { Mock } from 'vitest';
import type ObsidianMagicPlugin from '../main';
@@ -122,11 +113,5 @@
it('should render tags list with filter', () => {
- const mockContainer = {
- empty: vi.fn(),
- createEl: vi.fn().mockReturnThis(),
- createDiv: vi.fn().mockReturnThis(),
- createSpan: vi.fn().mockReturnThis(),
- setText: vi.fn(),
- } as unknown as MockContainer;
+ const mockContainer: MockObsidianElement<'div'> = createMockObsidianElement('div');
// Using "unknown" instead of "any" with a type assertion for the private method
Your Grace, I’ve removed the custom MockContainer definition and now utilize the shared MockObsidianElement<'div'> type from our stub. The test’s mockContainer is created via createMockObsidianElement, ensuring consistency with our mock utilities.
Your Humble Servant, Sebastien
User
We are still getting some test errors.
Assistant
Your Lordship,
The error Cannot read properties of undefined (reading 'forEach') in your test indicates that the files variable in getAllTags() is undefined. This happens because the mock for vault.getMarkdownFiles() is not returning the expected file objects, or the mock is not being used as intended.
Diagnosis:
In your test, you mock vault.getMarkdownFiles to return [ { path: 'note1.md' }, { path: 'note2.md' } ].
However, your getAllTags() expects these to be actual Obsidian TFile objects, or at least objects that the mocked metadataCache.getFileCache(file) can handle.
If getMarkdownFiles() returns undefined, files.forEach will throw.
Solution Plan:
Use the TFile mock from your __mocks__/obsidian.ts for the return value of getMarkdownFiles().
Ensure that metadataCache.getFileCache is mocked to handle these TFile objects.
Example Fix:
typescript
import { TFile } from '../__mocks__/obsidian';
// In your mockPlugin definition:
vault: {
getMarkdownFiles: vi.fn().mockReturnValue([
new TFile('note1.md'),
new TFile('note2.md'),
]),
},
Or, if your TFile constructor does not take a path, set the path property after creation:
Innovative Suggestion (Speculation):
You could create a helper in your mock to generate valid mock files for tests, ensuring all required properties are set, reducing boilerplate and future errors.
Would you like me to update the test setup to use the shared TFile mock and ensure the mocks are compatible, Your Lordship?
Your Humble Servant, Sebastien.
User
I want to update the @obsidian.ts so that it correctly handls the mocking for us.
Assistant
Your Lordship,
Here is my proposed plan to update @obsidian.ts (your manual Obsidian mock) so that it provides robust, ready-to-use mocks for TFile, Vault.getMarkdownFiles(), and MetadataCache.getFileCache()—eliminating the need for repetitive manual setup in each test.
Plan for Improving @obsidian.ts Mock
Enhance TFile Construction
Allow TFile to accept a path (and optionally name) in its constructor for easier instantiation in tests.
Add a Helper: createMockMarkdownFiles
Export a function that returns an array of TFile objects with valid paths/names.
Improve Vault.getMarkdownFiles()
By default, return a non-empty array of mock TFile objects (using the helper above).
Allow override for custom test cases.
Improve MetadataCache.getFileCache()
Return a mock file cache object with frontmatter and tags for any TFile input.
Optionally, allow per-file overrides via a map or function.
Document the Usage
Add JSDoc comments so test authors know how to use/override the mocks.
@@ -71,4 +71,27 @@
return el;
}
+
+ /**
+ * Minimal TFile stub with path and name for markdown file mocking.
+ * @example
+ * const file = new TFile('note1.md');
+ */
+ export class TFile {
+ path: string;
+ name: string;
+ constructor(path = 'mock.md', name?: string) {
+ this.path = path;
+ this.name = name ?? path.replace(/^.*[\\/]/, '').replace(/\.md$/, '');
+ }
+ }
+
+ /**
+ * Helper to create an array of mock markdown files.
+ * @param count Number of files to create
+ * @returns TFile[]
+ */
+ export function createMockMarkdownFiles(count = 2): TFile[] {
+ return Array.from({ length: count }, (_, i) => new TFile(`note${i + 1}.md`));
+ }
/** Minimal TFolder stub */
Chunk 2
Lines added: 15, lines removed: 3
diff
@@ -218,11 +241,23 @@
}
- /** Minimal MetadataCache stub */
+ /**
+ * Minimal MetadataCache stub with getFileCache returning a valid mock cache for any TFile.
+ * @example
+ * const cache = new MetadataCache();
+ * const fileCache = cache.getFileCache(file);
+ */
export class MetadataCache {
on(): { unsubscribe: () => void } {
return { unsubscribe: () => {} };
}
- getFileCache(): null {
- return null;
+ /**
+ * Returns a mock file cache object for any TFile.
+ * Override in tests if you need custom cache data.
+ */
+ getFileCache(_file?: TFile): any {
+ return {
+ frontmatter: { tags: ['test-tag'] },
+ tags: [{ tag: '#inline-tag', position: { start: { line: 5 } } }],
+ };
}
getCache(): null {
User
Can we mock TFile and TFolder using the actual classes?
Assistant
Your Lordship,
Yes, you can—and should—mock TFile and TFolder by importing the actual classes from the real obsidian package, rather than redeclaring them in your mock. This will:
Eliminate the “declaration conflict” and “type incompatibility” errors.
Ensure your mocks are always structurally compatible with the real Obsidian API.
Allow you to focus your mocking on behaviors and data, not on class shape.
How to do it:
Remove your local TFile and TFolder class definitions from __mocks__/obsidian.ts.
Import them at the top of your mock file:
typescript
import { TFile, TFolder } from 'obsidian';
Use these real classes in your helpers and mocks:
typescript
export function createMockMarkdownFiles(count = 2): TFile[] {
return Array.from({ length: count }, (_, i) => {
const file = new TFile();
file.path = `note${i + 1}.md`;
file.basename = `note${i + 1}`;
file.extension = 'md';
// Set any other properties as needed for your tests
return file;
});
}
Caveats:
You may need to set required properties on the real TFile/TFolder instances, as their constructors may not accept all fields directly.
If the real classes are not constructible (e.g., their constructors are private or require complex arguments), you can use Object.create(TFile.prototype) and assign properties as needed.
Innovative Suggestion (Speculation):
If you want to avoid breakage from upstream changes, you could dynamically “extend” the real classes in your mock, adding only the properties/methods you need for your tests.
Would you like me to provide a concrete code example for your current setup, Your Lordship?
Your Humble Servant, Sebastien.
User
For the code present, we get this error:
code
Expected 0 arguments, but got 1.
How can I resolve this? If you propose a fix, please make it concise.
Assistant
Your Lordship,
The error occurs because the real TFile and TFolder constructors do not accept arguments. Fix:
Instantiate with new TFile() or new TFolder(), then assign properties directly.
@@ -73,5 +73,5 @@
/**
- * Minimal TFile stub with path and name for markdown file mocking.
+ * Minimal TFile stub with all required properties for markdown file mocking.
* @example
* const file = new TFile('note1.md');