Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add mock functions for testing and SSG #3437

Merged
merged 9 commits into from
Feb 13, 2022
5 changes: 5 additions & 0 deletions .changes/mock-functions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"tauri": minor
---

Provide functions to mock IPC calls during testing and static site generation.
33 changes: 33 additions & 0 deletions tooling/api/src/mocks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
interface IPCMessage {
cmd: string,
callback: number,
error: number,
[key: string]: unknown
}

export function mockIPC(cb: (cmd: string, args: Record<string, unknown>) => any): void {
if ("__TAURI_IPC__" in window)
throw new Error("window.__TAURI_IPC__ is already defined");

window.__TAURI_IPC__ = async ({ cmd, callback, error, ...args }: IPCMessage) => {
try {
// @ts-expect-error The function key is dynamic and therefore not typed
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
window[`_${callback}`](await cb(cmd, args));
} catch (err) {
// @ts-expect-error The function key is dynamic and therefore not typed
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
window[`_${error}`](err);
}
};
}

export function mockWindows(current: string, ...additionalWindows: string[]): void {
if ("__TAURI_METADATA__" in window)
throw new Error("window.__TAURI_METADATA__ is already defined");

window.__TAURI_METADATA__ = {
__windows: [current, ...additionalWindows].map((label) => ({ label })),
__currentWindow: { label: current },
};
}