跳至主要内容

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

参数

名称类型默认值描述
osNamestringundefined要模拟的操作系统,可以是 linux、macos 或 windows 之一
windowsProtocolSchemestring'https'在 Windows 上使用的方案,可以是 httphttps,默认为 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

参数

名称类型描述
currentstring此 JavaScript 上下文正在运行的窗口的标签。
...additionalWindowsstring[]应用程序拥有的其他窗口的标签。

返回值: void