Merge pull request #112 from nathonius/test/107/jest

Unit tests
This commit is contained in:
Nathan 2024-04-23 00:03:34 -04:00 committed by GitHub
commit 4ca024edf4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 4462 additions and 29 deletions

View file

@ -6,13 +6,14 @@ on:
jobs:
build:
uses: "./.github/workflows/build.yml"
lint:
check:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- name: Lint
- name: Lint and Test
run: |
npm install
npm run lint
npm run test

46
.gitignore vendored
View file

@ -1,22 +1,24 @@
# vscode
.vscode
# Intellij
*.iml
.idea
# npm
node_modules
# Don't include the compiled main.js file in the repo.
# They should be uploaded to GitHub releases instead.
main.js
# Exclude sourcemaps
*.map
# obsidian
data.json
# Exclude macOS Finder (System Explorer) View States
.DS_Store
# vscode
.vscode
# Intellij
*.iml
.idea
# npm
node_modules
# Don't include the compiled main.js file in the repo.
# They should be uploaded to GitHub releases instead.
main.js
# Exclude sourcemaps
*.map
# obsidian
data.json
# Exclude macOS Finder (System Explorer) View States
.DS_Store
coverage/

11
__mocks__/obsidian.ts Normal file
View file

@ -0,0 +1,11 @@
import { AppMock } from "./obsidian/App";
import { PluginMock } from "./obsidian/Plugin";
import { ModalMock } from "./obsidian/Modal";
import { PluginSettingTabMock } from "./obsidian/PluginSettingTab";
module.exports = {
App: AppMock,
Plugin: PluginMock,
Modal: ModalMock,
PluginSettingTab: PluginSettingTabMock,
};

25
__mocks__/obsidian/App.ts Normal file
View file

@ -0,0 +1,25 @@
import type { App, FileManager, Keymap, MetadataCache, Scope, UserEvent, Vault, Workspace } from "obsidian";
export class AppMock implements App {
get keymap(): Keymap {
throw new Error("Not implemented.");
}
get scope(): Scope {
throw new Error("Not implemented.");
}
get workspace(): Workspace {
throw new Error("Not implemented.");
}
get vault(): Vault {
throw new Error("Not implemented.");
}
get metadataCache(): MetadataCache {
throw new Error("Not implemented.");
}
get fileManager(): FileManager {
throw new Error("Not implemented.");
}
get lastEvent(): UserEvent | null {
throw new Error("Not implemented.");
}
}

View file

@ -0,0 +1,34 @@
import type { App, Scope } from "obsidian";
import type { Modal } from "obsidian";
export class ModalMock implements Modal {
constructor(public app: App) {}
get scope(): Scope {
throw new Error("Not implemented.");
}
get containerEl(): HTMLElement {
throw new Error("Not implemented.");
}
get modalEl(): HTMLElement {
throw new Error("Not implemented.");
}
get titleEl(): HTMLElement {
throw new Error("Not implemented.");
}
get contentEl(): HTMLElement {
throw new Error("Not implemented.");
}
shouldRestoreSelection: boolean = false;
open(): void {
throw new Error("Method not implemented.");
}
close(): void {
throw new Error("Method not implemented.");
}
onOpen(): void {
throw new Error("Method not implemented.");
}
onClose(): void {
throw new Error("Method not implemented.");
}
}

View file

@ -0,0 +1,120 @@
/* eslint-disable unused-imports/no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { jest } from "@jest/globals";
import type { Editor } from "codemirror";
import type {
App,
Command,
Component,
EditorSuggest,
EventRef,
HoverLinkSource,
ObsidianProtocolHandler,
Plugin,
PluginManifest,
ViewCreator,
} from "obsidian";
export class PluginMock implements Plugin {
public data: any = undefined;
public intervals: number[] = [];
public addSettingTab = jest.fn();
public registerEditorExtension = jest.fn();
public registerInterval = jest.fn((interval: number) => {
this.intervals.push(interval);
return interval;
});
public registerMarkdownCodeBlockProcessor = jest.fn(() => {
return jest.fn(() => Promise.resolve());
});
public registerMarkdownPostProcessor = jest.fn(() => {
return jest.fn(() => Promise.resolve());
});
constructor(
public app: App,
public manifest: PluginManifest,
) {}
addRibbonIcon(icon: string, title: string, callback: (evt: MouseEvent) => any): HTMLElement {
throw new Error("Method not implemented.");
}
addStatusBarItem(): HTMLElement {
throw new Error("Method not implemented.");
}
addCommand(command: Command): Command {
throw new Error("Method not implemented.");
}
registerView(type: string, viewCreator: ViewCreator): void {
throw new Error("Method not implemented.");
}
registerHoverLinkSource(id: string, info: HoverLinkSource): void {
throw new Error("Method not implemented.");
}
registerExtensions(extensions: string[], viewType: string): void {
throw new Error("Method not implemented.");
}
registerCodeMirror(callback: (cm: Editor) => any): void {
throw new Error("Method not implemented.");
}
registerObsidianProtocolHandler(action: string, handler: ObsidianProtocolHandler): void {
throw new Error("Method not implemented.");
}
registerEditorSuggest(editorSuggest: EditorSuggest<any>): void {
throw new Error("Method not implemented.");
}
loadData(): Promise<any> {
return Promise.resolve(this.data);
}
saveData(data: any): Promise<void> {
this.data = data;
return Promise.resolve();
}
load(): void {
throw new Error("Method not implemented.");
}
onload(): void {
throw new Error("Method not implemented.");
}
unload(): void {
throw new Error("Method not implemented.");
}
onunload(): void {
throw new Error("Method not implemented.");
}
addChild<T extends Component>(component: T): T {
throw new Error("Method not implemented.");
}
removeChild<T extends Component>(component: T): T {
throw new Error("Method not implemented.");
}
register(cb: () => any): void {
throw new Error("Method not implemented.");
}
registerEvent(eventRef: EventRef): void {
throw new Error("Method not implemented.");
}
registerDomEvent<K extends keyof WindowEventMap>(
el: Window,
type: K,
callback: (this: HTMLElement, ev: WindowEventMap[K]) => any,
options?: boolean | AddEventListenerOptions | undefined,
): void;
registerDomEvent<K extends keyof DocumentEventMap>(
el: Document,
type: K,
callback: (this: HTMLElement, ev: DocumentEventMap[K]) => any,
options?: boolean | AddEventListenerOptions | undefined,
): void;
registerDomEvent<K extends keyof HTMLElementEventMap>(
el: HTMLElement,
type: K,
callback: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any,
options?: boolean | AddEventListenerOptions | undefined,
): void;
registerDomEvent(el: unknown, type: unknown, callback: unknown, options?: unknown): void {
throw new Error("Method not implemented.");
}
}

View file

@ -0,0 +1,17 @@
import type { App, PluginSettingTab, Plugin } from "obsidian";
export class PluginSettingTabMock implements PluginSettingTab {
constructor(
public app: App,
public plugin: Plugin,
) {}
get containerEl(): HTMLElement {
throw new Error("Not implemented.");
}
display() {
throw new Error("Method not implemented.");
}
hide() {
throw new Error("Method not implemented.");
}
}

81
__mocks__/queue.ts Normal file
View file

@ -0,0 +1,81 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { EventListenerOrEventListenerObject, EventsMap, QueueEvent, QueueWorker } from "queue";
import type Queue from "queue";
import type { Options } from "queue";
export default class QueueMock implements Queue {
concurrency: number;
timeout: number;
autostart: boolean;
results: any[] | null;
length: number = 0;
constructor(options: Options) {
this.concurrency = options.concurrency ?? 1;
this.timeout = options.timeout ?? -1;
this.autostart = options.autostart ?? false;
this.results = options.results ?? [];
}
push(...workers: QueueWorker[]): number {
for (const worker of workers) {
void worker();
}
return 0;
}
unshift(...workers: QueueWorker[]): number {
throw new Error("Method not implemented.");
}
splice(start: number, deleteCount?: number | undefined): Queue;
splice(start: number, deleteCount: number, ...workers: QueueWorker[]): Queue;
splice(start: unknown, deleteCount?: unknown, ...rest: unknown[]): Queue {
throw new Error("Method not implemented.");
}
pop(): QueueWorker | undefined {
throw new Error("Method not implemented.");
}
shift(): QueueWorker | undefined {
throw new Error("Method not implemented.");
}
slice(start?: number | undefined, end?: number | undefined): Queue {
throw new Error("Method not implemented.");
}
reverse(): Queue {
throw new Error("Method not implemented.");
}
indexOf(searchElement: QueueWorker, fromIndex?: number | undefined): number {
throw new Error("Method not implemented.");
}
lastIndexOf(searchElement: QueueWorker, fromIndex?: number | undefined): number {
throw new Error("Method not implemented.");
}
start(callback: (error?: Error | undefined, results?: any[] | null | undefined) => void): void;
start(): Promise<{ error?: Error | undefined; results?: any[] | null | undefined }>;
start(): void;
start(callback?: unknown): void | Promise<{ error?: Error | undefined; results?: any[] | null | undefined }> {
throw new Error("Method not implemented.");
}
stop(): void {
throw new Error("Method not implemented.");
}
end(error?: Error | undefined): void {
throw new Error("Method not implemented.");
}
addEventListener<Event extends keyof EventsMap>(
name: Event,
callback: EventListenerOrEventListenerObject<QueueEvent<Event, EventsMap[Event]>>,
options?: boolean | AddEventListenerOptions | undefined,
): void {
throw new Error("Method not implemented.");
}
dispatchEvent<Event extends keyof EventsMap>(event: QueueEvent<Event, EventsMap[Event]>): boolean {
throw new Error("Method not implemented.");
}
removeEventListener<Event extends keyof EventsMap>(
name: Event,
callback: EventListenerOrEventListenerObject<QueueEvent<Event, EventsMap[Event]>>,
options?: boolean | EventListenerOptions | undefined,
): void {
throw new Error("Method not implemented.");
}
}

View file

@ -4,10 +4,11 @@ import eslint from "@eslint/js";
import tseslint from "typescript-eslint";
import UnusedImportsPlugin from "eslint-plugin-unused-imports";
import PrettierConfig from "eslint-config-prettier";
import JestPlugin from "eslint-plugin-jest";
export default tseslint.config(
{
ignores: ["node_modules/", "main.js", "eslint.config.mjs"],
ignores: ["node_modules/", "main.js", "esbuild.config.mjs", "eslint.config.mjs", "jest.config.mjs"],
},
eslint.configs.recommended,
tseslint.configs.eslintRecommended,
@ -21,6 +22,7 @@ export default tseslint.config(
},
plugins: {
"unused-imports": UnusedImportsPlugin,
jest: JestPlugin,
},
rules: {
"@typescript-eslint/restrict-template-expressions": "warn",
@ -28,7 +30,7 @@ export default tseslint.config(
"@typescript-eslint/no-unsafe-argument": "warn",
"@typescript-eslint/no-unsafe-member-access": "warn",
"@typescript-eslint/no-redundant-type-constituents": "warn",
"@typescript-eslint/unbound-method": "warn",
"@typescript-eslint/unbound-method": "off",
"@typescript-eslint/no-this-alias": "warn",
"@typescript-eslint/no-empty-function": "warn",
"@typescript-eslint/consistent-type-imports": "error",
@ -48,4 +50,11 @@ export default tseslint.config(
},
},
PrettierConfig,
{
files: ["**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[tj]s?(x)"],
...JestPlugin.configs["flat/recommended"],
rules: {
"@typescript-eslint/no-floating-promises": "off",
},
},
);

199
jest.config.mjs Normal file
View file

@ -0,0 +1,199 @@
/**
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/
const config = {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "/tmp/jest_rs",
// Automatically clear mock calls, instances, contexts and results before every test
// clearMocks: false,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: true,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "v8",
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "mjs",
// "cjs",
// "jsx",
// "ts",
// "tsx",
// "json",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
moduleNameMapper: {
"src/(.*)": "<rootDir>/src/$1",
},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
preset: "ts-jest",
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state before every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
testEnvironment: "jsdom",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
export default config;

3839
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -7,7 +7,8 @@
"dev": "node esbuild.config.mjs",
"build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production",
"version": "node version-bump.mjs && git add manifest.json versions.json",
"lint": "eslint src/"
"lint": "eslint src/",
"test": "jest"
},
"keywords": [],
"author": {
@ -18,15 +19,20 @@
"devDependencies": {
"@codemirror/view": "^6.23.0",
"@eslint/js": "^9.1.1",
"@jest/globals": "^29.7.0",
"@types/node": "^20.11.19",
"builtin-modules": "3.3.0",
"esbuild": "0.20.0",
"eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-jest": "^28.2.0",
"eslint-plugin-unused-imports": "^3.1.0",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"obsidian": "latest",
"octokit": "^3.1.2",
"prettier": "^3.2.5",
"ts-jest": "^29.1.2",
"tslib": "2.6.2",
"typescript": "^5.4.5",
"typescript-eslint": "^7.7.0"

88
src/plugin.spec.ts Normal file
View file

@ -0,0 +1,88 @@
import { expect, jest, test } from "@jest/globals";
import { GithubLinkPlugin, PluginData, PluginSettings, getCache } from "./plugin";
import { beforeEach, describe } from "node:test";
import type { Plugin, RequestUrlResponse } from "obsidian";
import { App } from "obsidian";
import * as manifest from "../manifest.json";
import type { PluginMock } from "__mocks__/obsidian/Plugin";
import type { GithubLinkPluginSettings } from "./settings";
import { DEFAULT_SETTINGS } from "./settings";
import { CacheEntry, RequestCache } from "./github/cache";
import { LogLevel } from "./logger";
jest.mock("./settings/settings-tab");
function mockedPlugin(plugin: GithubLinkPlugin): PluginMock {
return plugin as Plugin as PluginMock;
}
describe("GithubLinkPlugin", () => {
let app: App;
let plugin: GithubLinkPlugin;
beforeEach(() => {
app = new App();
});
test("should create", () => {
plugin = new GithubLinkPlugin(app, manifest);
expect(plugin).toBeTruthy();
});
test("should create cache instance", async () => {
plugin = new GithubLinkPlugin(app, manifest);
await plugin.onload();
expect(getCache() instanceof RequestCache).toBeTruthy();
});
test("should load all required components", async () => {
plugin = new GithubLinkPlugin(app, manifest);
await plugin.onload();
expect(plugin.addSettingTab).toHaveBeenCalled();
expect(plugin.registerMarkdownPostProcessor).toHaveBeenCalled();
expect(plugin.registerEditorExtension).toHaveBeenCalled();
expect(plugin.registerMarkdownCodeBlockProcessor).toHaveBeenCalled();
expect(plugin.registerInterval).toHaveBeenCalled();
});
describe("loadData", () => {
test("should initialize default settings", async () => {
plugin = new GithubLinkPlugin(app, manifest);
await plugin.onload();
expect(PluginData).toBeDefined();
expect(PluginData.cache).toEqual(null);
expect(PluginData.settings).toEqual(DEFAULT_SETTINGS);
});
test("should load stored cache", async () => {
const cacheEntry = new CacheEntry(
{ url: "mock" },
{ json: "mock" } as RequestUrlResponse,
new Date(),
null,
null,
);
plugin = new GithubLinkPlugin(app, manifest);
mockedPlugin(plugin).data = { cache: [cacheEntry.toJSON()] };
await plugin.onload();
expect(PluginData.cache).toEqual([cacheEntry.toJSON()]);
expect(getCache().get(cacheEntry.request)).toEqual(cacheEntry);
});
test.each<{ stored: Partial<GithubLinkPluginSettings>; name: string }>([
{ stored: { cacheIntervalSeconds: 69 }, name: "cacheIntervalSeconds" },
{ stored: { defaultPageSize: 69 }, name: "defaultPageSize" },
{ stored: { tagTooltips: true }, name: "tagTooltips" },
{ stored: { tagTooltips: false }, name: "tagTooltips" },
{ stored: { minRequestSeconds: 69 }, name: "minRequestSeconds" },
{ stored: { logLevel: LogLevel.Debug }, name: "logLevel" },
])("should merge stored and default settings ($name)", async ({ stored }) => {
plugin = new GithubLinkPlugin(app, manifest);
mockedPlugin(plugin).data = { settings: stored };
await plugin.onload();
for (const [k, v] of Object.entries(stored)) {
expect(PluginSettings[k as keyof GithubLinkPluginSettings]).toEqual(v);
}
});
});
});

View file

@ -1,4 +1,4 @@
import { LogLevel } from "src/logger";
import { LogLevel } from "../logger";
export interface GithubAccount {
id: string;

View file

@ -12,7 +12,8 @@
"isolatedModules": true,
"strict": true,
"strictNullChecks": true,
"lib": ["DOM", "ES5", "ES6", "ES7"]
"lib": ["DOM", "ES5", "ES6", "ES7"],
"resolveJsonModule": true
},
"include": ["**/*.ts"]
}