DataScience
article thumbnail
Published 2023. 4. 14. 09:30
Tauri 테스트 Rust
728x90

1. Tauri API 모킹

프론트엔드 테스트를 작성할 때 "가짜" Tauri 환경을 사용하여 창을 모의 시험하거나 IPC 호출을 가로채는 것이 일반적이며 이를 mocking이라고 합니다.

IPC 요청
mockIPC() 와 함께 다른 탐색, 모킹 도구를 사용할 수 있습니다.

<code />
import { beforeAll, expect, test, vi } from "vitest"; import { randomFillSync } from "crypto"; import { mockIPC } from "@tauri-apps/api/mocks"; import { invoke } from "@tauri-apps/api/tauri"; // jsdom doesn't come with a WebCrypto implementation beforeAll(() => { //@ts-ignore window.crypto = { getRandomValues: function (buffer) { return randomFillSync(buffer); }, }; }); test("invoke", async () => { mockIPC((cmd, args) => { // simulated rust command called "add" that just adds two numbers if(cmd === "add") { return (args.a as number) + (args.b as number); } }); // we can use the spying tools provided by vitest to track the mocked function const spy = vi.spyOn(window, "__TAURI_IPC__"); expect(invoke("add", { a: 12, b: 15 })).resolves.toBe(27); expect(spy).toHaveBeenCalled(); });

사이드카 또는 셸 명령에 대한 IPC 요청을 모방하려면 spawn()이나 execute()가 호출될 때 이벤트 핸들러의 ID를 가져와 이 ID를 사용하여 백엔드가 다시 보낼 이벤트를 내보내야 합니다:

<code />
mockIPC(async (cmd, args) => { if (args.message.cmd === 'execute') { const eventCallbackId = `_${args.message.onEventFn}`; const eventEmitter = window[eventCallbackId]; // 'Stdout' event can be called multiple times eventEmitter({ event: 'Stdout', payload: 'some data sent from the process', }); // 'Terminated' event must be called at the end to resolve the promise eventEmitter({ event: 'Terminated', payload: { code: 0, signal: 'kill', }, }); } });

Windows
가짜 윈도우 레이블을 생성하기 위해 mockWindows() 함수를 사용할 수 있습니다.

<code />
import { beforeAll, expect, test } from 'vitest'; import { randomFillSync } from 'crypto'; import { mockWindows } from '@tauri-apps/api/mocks'; // jsdom doesn't come with a WebCrypto implementation beforeAll(() => { //@ts-ignore window.crypto = { getRandomValues: function (buffer) { return randomFillSync(buffer); }, } }); test('invoke', async () => { mockWindows('main', 'second', 'third'); const { getCurrent, getAll } = await import('@tauri-apps/api/window'); expect(getCurrent()).toHaveProperty('label', 'main'); expect(getAll().map((w) => w.label)).toEqual(['main', 'second', 'third']); });

'Rust' 카테고리의 다른 글

Tauri 배포  (53) 2023.04.15
Tauri 빌드  (110) 2023.04.14
Tauri 디버깅  (106) 2023.04.13
Tauri 개발  (31) 2023.04.13
Tauri 구조  (135) 2023.04.12
profile

DataScience

@Ninestar

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!