Tests

From trezor/trezor-suite · View interactive version

Tests is an AI agent skill from the GitHub repository trezor/trezor-suite. Test style guidelines including naming conventions, mock organization, dispatch and thunk testing, translation handling, and file structure. Use when writing or organizing tests in the Trezor Suite codebase.

How to use this skill

Skill file

Tests

Reading

Translations in tests

Text in the app may change as translators and copywriters update strings in Crowdin, independently of developers. To

avoid failing tests in Crowdin sync PRs, get the string by its translation ID instead of using the literal text.

// bad
expect(
    screen.getByText('This can change with a Crowdin sync and someone will have to fix the test.'),
).toBeTruthy();

// good
expect(screen.getByText(getTranslation('path.to.translation'))).toBeTruthy();

// In case there is some string that must not be changed:
expect(screen.getByText(getTranslation('path.to.translation'))).toBe(
    'I want a developer to check this important text if it is changed in Crowdin.',
);

Naming conventions

you should immediately see whether it has a nearby test.

(For example: typedObjectFromEntries.type-test.ts)

Example:

my-module/
├── mocks/
│   └── mockMyComponent.ts
└── src/
    ├── MyComponent.tsx
    ├── MyComponent.test.tsx
    ├── useMyData.ts
    ├── useMyData.test.ts
    ├── utils.ts
    └── utils.test.ts

Reusability

To keep things simple, avoid creating complex mocks to be shared between multiple test suites. In case you do reuse a

mock, keep it generic and non-opinionated.

Simple test: change in shared mock SHALL NOT break existing tests (or make fixes trivial).

Type tests

Keep type-test assertions module-local. Do not export test-only values or types, because exports

pollute the generated declaration files. Use void statements to mark assertion values as used:

const valid: ExpectedType = value;

// @ts-expect-error The value must not accept an incompatible type.
const invalid: ExpectedType = incompatibleValue;

void valid;
void invalid;

Mocks (& Fixtures)

Typing

All fixtures and mocks shall be typed and declaratively defined; using as to cast an incomplete object is only a last

resort. This may add boilerplate, but it ensures type changes surface as type errors instead of hard-to-fix failing

tests.

Organization & Naming Convention

is located.

changes. (mockDevice(data: Partial<Device>): Device => ({ ... }))

import { mockDevice } from '@common/device-types/mocks'

```

device-types

```

Dependencies in tests

Always use declared dependency types

Test dependency objects (deps, thunk extra, provider services, etc.) MUST use the subject's

declared, named dependency type. Reuse its exported type; export it if needed instead of redefining

it in the test.

When assigning an object literal, annotate the variable explicitly: const deps: SubjectDeps = { ... },

const extra: SubjectExtra = { ... } or const services: SubjectServices = { ... }.

const services: NativeAnalyticsDep = {
    analytics: mockNativeAnalytics(mock()),
};

With createMockDeps<SubjectDeps>, the generic argument supplies the dependency type; do not repeat

it as a variable annotation.

Use DI mock helpers whenever possible

Tests MUST use createMockDeps and mock from @trezor/dependency-injection wherever

applicable. Use bare jest.fn only when these helpers cannot represent the required mock.

use null for functions that must throw if called. Assert directly on the returned mocks.

const deps = createMockDeps<WriteAccountLabelDeps>({
    analytics: { report: null },
    getAccountLabel: () => null,
});

Shared service mock factories in the package's mocks directory MUST also use mock, using the

service contract as the type argument:

export const mockGetHttpReceiverAddress = (address = 'http://localhost:21325') =>
    mock<DesktopApi['getHttpReceiverAddress']>(() => Promise.resolve(address));

Dispatch in tests

Every dispatch in a test comes from createMockDispatch or from a store built by the platform

test utilities. Pick by what the test asserts:

| The test asserts | dispatch comes from |

| ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

| which actions were dispatched, which services called | createMockDispatch from @trezor/redux-utils/mocks |

| the state or UI after reducers and middleware ran | createTestCompositionRoot (guide); in native, createLightStore (Native tests) |

createMockDispatch({ getState, extra }) returns { actions, dispatch, onDispatch }. dispatch

pushes every plain action to actions and runs every dispatched thunk, nested ones included, with

the same dispatch, getState and extra.

A thunk

Redux calls a thunk with dispatch, getState and extra; the unit test passes those three

itself. Build getState and extra from the thunk's exported contracts and keep the fixture local

to the test:

const state: XyzThunkState = {
    // Only the state required by xyzThunk.
};
const extra: XyzThunkDeps = {
    services: {
        // Only the services required by xyzThunk.
    },
};
const getState = () => state;
const { actions, dispatch } = createMockDispatch({ getState, extra });

await xyzThunk()(dispatch, getState, extra);

expect(extra.services.someService).toHaveBeenCalled();
expect(actions).toEqual([
    expect.objectContaining({ type: xyzThunk.pending.type }),
    expect.objectContaining({ type: xyzThunk.fulfilled.type }),
]);

A hook or component that dispatches

Render it with the platform store provider, and swap the store's dispatch for the mock one so the

test can assert on actions:

const store = createStoreFromPreloadedState(preloadedState);
const { actions, dispatch } = createMockDispatch({ getState: store.getState, extra: undefined });

const { result } = await renderHookWithStoreProvider(() => useXyz(), {
    services: { store: { ...store, dispatch } },
});

await act(() => result.current.submit());

expect(actions).toContainEqual(xyzActions.submitted());

A thunk the test replaces with jest.mock still goes through this dispatch: the mock thunk is

called with the same three arguments.

Waiting for a dispatched action

Production code often ignores what dispatch returns, so awaiting the trigger does not wait for the

thunk. Subscribe with onDispatch before triggering, call resolve on the action the test waits

for, and await the subscription:

const finished = onDispatch((action, resolve) => {
    if (action.type === xyzThunk.fulfilled.type) resolve();
});

triggerTheCodeUnderTest();

await finished;

A subscription that is neither awaited nor unsubscribed fails the test.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.