Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 39 Β· Testing and Updates

Testing Tauri Apps: Rust Tests and Mocked IPC

Test a Tauri app on both sides: Rust unit and integration tests with the mock runtime, frontend tests with mockIPC and mockWindows, test design tips, and runnable examples using node:test.

A Tauri app is two programs that talk to each other: a Rust core and a web frontend. The good news is that you can test each side by itself, quickly, without opening a window. You pretend to be the other side. Rust tests call your commands directly or through a mock runtime; frontend tests replace Tauri's message channel with mocked IPC, so components think they are talking to Rust.

This lesson shows both techniques and how to design code so it is easy to test. The next lesson, End-to-End Testing and CI, covers tests of the real, running app.

Real versus stand-in. The rust and ts snippets are real Tauri 2 test code. The runnable blocks use Node's built-in test runner on small stand-ins, so you can see the pattern working here.

Design for testing: keep logic out of the glue

A #[tauri::command] function should be thin. Put the actual work in a plain Rust function that knows nothing about Tauri, and call it from the command.

Rust
// src-tauri/src/notes.rs: pure logic, easy to test
pub fn word_count(text: &str) -> usize {
    text.split_whitespace().count()
}

pub fn slugify(title: &str) -> String {
    let mut out = String::new();
    for ch in title.trim().chars() {
        if ch.is_ascii_alphanumeric() {
            out.push(ch.to_ascii_lowercase());
        } else if !out.ends_with('-') && !out.is_empty() {
            out.push('-');
        }
    }
    out.trim_end_matches('-').to_string()
}

// src-tauri/src/lib.rs: thin command
#[tauri::command]
fn note_stats(text: String) -> usize {
    notes::word_count(&text)
}

Then unit tests sit beside the code and run with plain cargo test:

Rust
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn counts_words() {
        assert_eq!(word_count("  hello   brave new world "), 4);
        assert_eq!(word_count(""), 0);
    }

    #[test]
    fn slugs_are_clean() {
        assert_eq!(slugify("  Hello, World!  "), "hello-world");
        assert_eq!(slugify("***"), "");
    }
}
Terminal
cd src-tauri && cargo test

Testing commands with the mock runtime

Some commands need an AppHandle, state, events or windows. Tauri ships a test module (tauri::test) with a mock runtime that behaves like the real one without a webview. Enable it in Cargo.toml for tests:

TOML
[dev-dependencies]
tauri = { version = "2", features = ["test"] }
Rust
#[cfg(test)]
mod tests {
    use super::*;
    use tauri::test::{mock_builder, mock_context, noop_assets, get_ipc_response, INVOKE_KEY};
    use tauri::webview::InvokeRequest;

    fn app() -> tauri::App<tauri::test::MockRuntime> {
        mock_builder()
            .manage(CounterState::default())
            .invoke_handler(tauri::generate_handler![increment, current])
            .build(mock_context(noop_assets()))
            .expect("failed to build mock app")
    }

    #[test]
    fn increment_changes_state() {
        let app = app();
        let webview = tauri::WebviewWindowBuilder::new(&app, "main", Default::default())
            .build()
            .unwrap();

        let response = get_ipc_response(
            &webview,
            InvokeRequest {
                cmd: "increment".into(),
                callback: tauri::ipc::CallbackFn(0),
                error: tauri::ipc::CallbackFn(1),
                url: "http://tauri.localhost".parse().unwrap(),
                body: tauri::ipc::InvokeBody::Json(serde_json::json!({ "by": 5 })),
                headers: Default::default(),
                invoke_key: INVOKE_KEY.to_string(),
            },
        );
        assert_eq!(response.unwrap().deserialize::<i64>().unwrap(), 5);
    }
}

get_ipc_response sends a request through the same IPC pipeline as production, including argument deserialization, so mistakes in argument names are caught. Because the setup is verbose, wrap it in a helper in your own test module. The state and async patterns from Writing a Custom Plugin apply here too.

Good Rust tests check three things per command: the happy path, each validation error (see Scopes and Input Validation), and any state or event changes.

Frontend tests with mockIPC

On the JavaScript side, @tauri-apps/api/mocks replaces the real channel. You write a function that receives the command name and arguments, and returns what Rust would return:

TypeScript
import { mockIPC, clearMocks } from '@tauri-apps/api/mocks';
import { invoke } from '@tauri-apps/api/core';
import { afterEach, expect, test, vi } from 'vitest';

afterEach(() => clearMocks());

test('loads notes through the list_notes command', async () => {
  mockIPC((cmd, args) => {
    if (cmd === 'list_notes') {
      return [{ id: 1, title: 'Plan' }, { id: 2, title: 'Ideas' }];
    }
  });

  const notes = await invoke<{ id: number; title: string }[]>('list_notes');
  expect(notes).toHaveLength(2);
});

test('sends the right arguments', async () => {
  const spy = vi.fn();
  mockIPC((cmd, args) => {
    spy(cmd, args);
    return null;
  });
  await invoke('save_note', { id: 7, body: 'hello' });
  expect(spy).toHaveBeenCalledWith('save_note', { id: 7, body: 'hello' });
});

Other helpers:

  • mockWindows('main', 'settings') pretends those windows exist, so code that reads the current window label works.
  • mockConvertFileSrc('linux') fakes how file paths become URLs.
  • mockIPC(handler, { shouldMockEvents: true }) also lets emit and listen work.
  • Reject errors by throwing or returning a rejected promise, to test your error UI.

The stand-in below builds the same trick: a mockable invoke, a component function that uses it, and tests using node:test. It runs here the same way vitest would run yours.

Node.js Stand-in: mockIPC with node:test

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Testing the same logic in Rust and JavaScript

Pure functions are the cheapest tests of all, in either language. Here is the slug function from the Rust example in JavaScript, with a table of cases. Writing the cases as a table means adding one more costs one line.

Node.js Stand-in: table-driven tests of a pure function

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

What to test, what to skip

Test Tool Speed
Pure Rust logic cargo test milliseconds
Commands with state and events mock runtime milliseconds
Components calling invoke vitest/jest with mockIPC milliseconds
Real app, real webview, clicks WebDriver (see the next lesson) seconds

Do not try to test Tauri itself or the operating system dialogs; test your logic and your use of the API. Mock native features (dialogs, file pickers) at the boundary, and keep a few end-to-end tests for the journeys that matter most.

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. What is the best way to make a Tauri command easy to test?

    Plain functions need no app or runtime, so tests are small and fast.
  2. 2. What does mockIPC from @tauri-apps/api/mocks do?

    Frontend tests then run without a real Tauri backend, returning whatever data the test needs.
  3. 3. Which Cargo feature gives you the mock runtime for Rust tests?

    The test feature enables tauri::test with mock_builder, mock_context and helpers.
  4. 4. How should you test your error UI when Rust fails?

    A mock that throws lets you test failure paths deterministically.

Summary

  • Keep logic in plain functions; commands stay thin.
  • Rust: cargo test for logic, tauri::test mock runtime for commands needing state, events or windows.
  • Frontend: mockIPC, mockWindows and clearMocks isolate components from Rust.
  • Test happy paths, validation errors and failures; mock native dialogs at the boundary.

Next: End-to-End Testing and CI