mocks
函式
clearMocks
clearMocks():
void
清除此模組中其他函式注入的模擬函式/資料。當使用未針對每個測試提供全新視窗物件的測試執行器時,呼叫此函式將重設特定於 Tauri 的屬性。
範例
import { mockWindows, clearMocks } from "@tauri-apps/api/mocks"
afterEach(() => {
clearMocks()
})
test("mocked windows", () => {
mockWindows("main", "second", "third");
expect(window).toHaveProperty("__TAURI_METADATA__")
})
test("no mocked windows", () => {
expect(window).not.toHaveProperty("__TAURI_METADATA__")
})
自: 1.0.0
傳回:void
mockConvertFileSrc
mockConvertFileSrc(
osName
:string
,windowsProtocolScheme?
:string
):void
模擬 convertFileSrc
函式
範例
import { mockConvertFileSrc } from "@tauri-apps/api/mocks";
import { convertFileSrc } from "@tauri-apps/api/tauri";
mockConvertFileSrc("windows")
const url = convertFileSrc("C:\\Users\\user\\file.txt")
自: 1.6.0
參數
名稱 | 類型 | 預設值 | 說明 |
---|---|---|---|
osName | string | 未定義 | 要模擬的操作系統,可以是 linux、macos 或 windows 之一 |
windowsProtocolScheme | string | 'https' | 在 Windows 上使用的協定,可以是 http 或 https ,預設為 https |
傳回:void
mockIPC
mockIPC(
cb
:fn
):void
使用指定的模擬處理常式攔截所有 IPC 要求。
在測試 Tauri 前端應用程式或在靜態網站產生期間在 Node.js 環境中執行前端時,可以使用此函式。
範例
使用 vitest 進行測試設定
import { mockIPC, clearMocks } from "@tauri-apps/api/mocks"
import { invoke } from "@tauri-apps/api/tauri"
afterEach(() => {
clearMocks()
})
test("mocked command", () => {
mockIPC((cmd, args) => {
switch (cmd) {
case "add":
return (args.a as number) + (args.b as number);
default:
break;
}
});
expect(invoke('add', { a: 12, b: 15 })).resolves.toBe(27);
})
呼叫回函式也可以傳回 Promise
import { mockIPC, clearMocks } from "@tauri-apps/api/mocks"
import { invoke } from "@tauri-apps/api/tauri"
afterEach(() => {
clearMocks()
})
test("mocked command", () => {
mockIPC((cmd, args) => {
if(cmd === "get_data") {
return fetch("https://example.com/data.json")
.then((response) => response.json())
}
});
expect(invoke('get_data')).resolves.toBe({ foo: 'bar' });
})
自: 1.0.0
參數
名稱 | 類型 |
---|---|
cb | (cmd : string , args : Record <string , unknown >) => any |
傳回:void
mockWindows
mockWindows(
current
:string
, ...additionalWindows
:string
[]):void
模擬一個或多個視窗標籤。在非 Tauri 環境中,必須在使用 @tauri-apps/api/window
模組之前呼叫此函式。
此函式僅模擬視窗的存在,視窗屬性(例如寬度和高度)可以使用 mockIPC
函式模擬,就像一般的 IPC 呼叫。
範例
import { mockWindows } from "@tauri-apps/api/mocks";
import { getCurrent } from "@tauri-apps/api/window";
mockWindows("main", "second", "third");
const win = getCurrent();
win.label // "main"
import { mockWindows } from "@tauri-apps/api/mocks";
mockWindows("main", "second", "third");
mockIPC((cmd, args) => {
if (cmd === "tauri") {
if (
args?.__tauriModule === "Window" &&
args?.message?.cmd === "manage" &&
args?.message?.data?.cmd?.type === "close"
) {
console.log('closing window!');
}
}
});
const { getCurrent } = await import("@tauri-apps/api/window");
const win = getCurrent();
await win.close(); // this will cause the mocked IPC handler to log to the console.
自: 1.0.0
參數
名稱 | 類型 | 說明 |
---|---|---|
current | string | 此 JavaScript 內容執行的視窗標籤。 |
...additionalWindows | string [] | 應用程式所擁有的其他視窗標籤。 |
傳回:void