Skip to content

docs(mocking): add note about event mocking #3395

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

Open
wants to merge 3 commits into
base: v2
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ sidebar:
order: 10
i18nReady: true
---
import SinceVersion from '../../../../components/SinceVersion.astro';


When writing your frontend tests, having a "fake" Tauri environment to simulate windows or intercept IPC calls is common, so-called _mocking_.
The [`@tauri-apps/api/mocks`] module provides some helpful tools to make this easier for you:
Expand All @@ -29,6 +31,8 @@ The following examples use [Vitest], but you can use any other frontend testing

:::

### Mocking Commands for `invoke`

```javascript
import { beforeAll, expect, test } from "vitest";
import { randomFillSync } from "crypto";
Expand Down Expand Up @@ -124,6 +128,33 @@ mockIPC(async (cmd, args) => {
});
```

### Mocking Events

<SinceVersion version="2.7.0"/>

There is partial support of the [Event System] to simulate events emitted by your Rust code via the `shouldMockEvents` option:

```javascript
import { mockIPC, clearMocks } from "@tauri-apps/api/mocks"
import { emit, listen } from "@tauri-apps/api/event"
import { afterEach, expect, test, vi } from "vitest"

test("mocked event", () => {
mockIPC(() => {}, { shouldMockEvents: true }); // enable event mocking

const eventHandler = vi.fn();
listen('test-event', eventHandler);

emit('test-event', { foo: 'bar' });
expect(eventHandler).toHaveBeenCalledWith({
event: 'test-event',
payload: { foo: 'bar' }
});
})
```
`emitTo` and `emit_filter` are **not** supported yet.


## Windows

Sometimes you have window-specific code (a splash screen window, for example), so you need to simulate different windows.
Expand Down Expand Up @@ -168,3 +199,4 @@ test('invoke', async () => {
[`mockwindows()`]: /reference/javascript/api/namespacemocks/#mockwindows
[`clearmocks()`]: /reference/javascript/api/namespacemocks/#clearmocks
[vitest]: https://vitest.dev
[Event System]: /develop/calling-frontend/#event-system
Loading