Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
ecd05ec
feat: add automated test suite PoC — 57 tests across 3 layers
tuliomir Apr 28, 2026
8f9eeb2
fix: make entire test suite pass — fix pre-existing test failures
tuliomir Apr 14, 2026
67c4b44
chore: allow-scripts entry for jest-circus's unrs-resolver
tuliomir Apr 28, 2026
4f4e9d3
fix: align reown.test.js with rejectAll saga's actual yield order
tuliomir Apr 28, 2026
bdbf958
test: add slice-refactor safety net + testing guide
tuliomir Apr 28, 2026
49a4e57
chore: address review nits + pin jest-circus
tuliomir Apr 28, 2026
ec3b546
docs: annotate review findings that were intentionally not fixed
tuliomir Apr 28, 2026
940f684
fix(ci): regenerate package-lock.json with Node 22
tuliomir Apr 28, 2026
0864921
fix(lint): import jest globals in reducer test files
tuliomir Apr 28, 2026
d19358e
chore: address second review pass — lint hygiene + duplicate test
tuliomir Apr 28, 2026
26638c6
test: address third-pass review — strengthen contracts, dedupe helper
tuliomir Apr 28, 2026
ee6848a
docs: add AGENTS.md, CLAUDE.md, and writing-tests skill
tuliomir Apr 28, 2026
7a20c5f
docs: refine test docs per QA audit — gotchas first, less filler
tuliomir Apr 28, 2026
d5ff9f0
fix(test): address CodeRabbit lint findings on PR #863
tuliomir Apr 28, 2026
86e8352
test: restore nanoContract coverage lost in 8f9eeb2
tuliomir Apr 28, 2026
037b6e8
fix(test): import jest globals in utils + InitWallet tests
tuliomir Apr 28, 2026
1c6dc07
fix(test): address CodeRabbit lint findings on screen tests
tuliomir Apr 29, 2026
adeff1a
test: tighten screen test contracts per CodeRabbit nitpicks
tuliomir Apr 29, 2026
1e114e7
fix: address Copilot review on PR #863
tuliomir Apr 29, 2026
a5ae036
docs: break circular AGENTS.md ↔ CLAUDE.md pointer
tuliomir Apr 29, 2026
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
13 changes: 12 additions & 1 deletion __tests__/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,18 @@ import renderer from 'react-test-renderer';

jest.mock('redux-saga', () => () => ({ run: jest.fn() }));
jest.mock('redux', () => ({
createStore: jest.fn(),
createStore: jest.fn(() => ({
getState: jest.fn(() => ({})),
dispatch: jest.fn(),
subscribe: jest.fn(),
replaceReducer: jest.fn(),
})),
legacy_createStore: jest.fn(() => ({
getState: jest.fn(() => ({})),
dispatch: jest.fn(),
subscribe: jest.fn(),
replaceReducer: jest.fn(),
})),
applyMiddleware: jest.fn(),
}));

Expand Down
67 changes: 67 additions & 0 deletions __tests__/helpers/mockNavigation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/**
* Test helper: mock navigation objects for React Navigation 7.
*
* Provides mock implementations of useNavigation and useRoute that
* components can call without a real NavigationContainer.
*/
import { jest } from '@jest/globals';

export function createMockNavigation() {
return {
navigate: jest.fn(),
push: jest.fn(),
replace: jest.fn(),
goBack: jest.fn(),
reset: jest.fn(),
setOptions: jest.fn(),
setParams: jest.fn(),
dispatch: jest.fn(),
addListener: jest.fn(() => jest.fn()), // returns unsubscribe
canGoBack: jest.fn(() => true),
isFocused: jest.fn(() => true),
getParent: jest.fn(),
getState: jest.fn(() => ({
index: 0,
routes: [{ name: 'MockRoute', key: 'mock-key' }],
})),
};
}

export function createMockRoute(params: Record<string, unknown> = {}) {
return {
key: 'mock-route-key',
name: 'MockRoute',
params,
};
}

/**
* Setup jest mocks for both React Navigation's native hooks
* and the app's custom BigInt-aware hooks in src/hooks/navigation.js.
*
* Call this in a beforeEach or at module scope in your test file.
*
* @returns Object with references to the mocks for assertion.
*/
export function setupNavigationMocks(routeParams: Record<string, unknown> = {}) {
const mockNav = createMockNavigation();
const mockRoute = createMockRoute(routeParams);

// Mock React Navigation's native hooks
jest.mock('@react-navigation/native', () => {
const actual = jest.requireActual('@react-navigation/native') as any;
return {
...actual,
useNavigation: () => mockNav,
useRoute: () => mockRoute,
};
});

// Mock the app's custom hooks (which wrap the above with BigInt handling)
jest.mock('../../src/hooks/navigation', () => ({
useNavigation: () => mockNav,
useParams: () => mockRoute.params,
}));

return { navigation: mockNav, route: mockRoute };
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated
21 changes: 21 additions & 0 deletions __tests__/helpers/mockStore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* Test helper: creates a Redux store with optional preloaded state.
*
* Uses the real reducer from the app so that dispatched actions
* produce the same state transitions as production code.
*/
import { legacy_createStore as createStore } from 'redux';
import { reducer } from '../../src/reducers/reducer';

/**
* Create a Redux store for testing with optional state overrides.
*
* @param preloadedState - Partial state merged on top of the reducer's
* built-in initialState. Pass only the keys you care about.
*/
export function createTestStore(preloadedState: Record<string, unknown> = {}) {
// Dispatching an unknown action returns initialState from the reducer,
// which we then merge with the caller's overrides.
const baseState = reducer(undefined, { type: '@@INIT' });
return createStore(reducer, { ...baseState, ...preloadedState } as any);
}
46 changes: 46 additions & 0 deletions __tests__/helpers/renderWithProviders.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/**
* Test helper: renders a React component wrapped in all the providers
* that the Hathor Wallet app expects (Redux, Navigation).
*
* Usage:
* const { getByText } = renderWithProviders(<MyScreen />, {
* preloadedState: { isOnline: true },
* });
*/
import React from 'react';
import { render, RenderOptions } from '@testing-library/react-native';
import { Provider } from 'react-redux';
import { NavigationContainer } from '@react-navigation/native';
import { createTestStore } from './mockStore';

interface ExtendedRenderOptions extends Omit<RenderOptions, 'wrapper'> {
/** Partial Redux state merged on top of initialState. */
preloadedState?: Record<string, unknown>;
/** Supply your own store (e.g. if you need to dispatch in the test). */
store?: ReturnType<typeof createTestStore>;
/** If false, skip wrapping in NavigationContainer (default: true). */
withNavigation?: boolean;
}

export function renderWithProviders(
ui: React.ReactElement,
{
preloadedState = {},
store = createTestStore(preloadedState),
withNavigation = true,
...renderOptions
}: ExtendedRenderOptions = {},
) {
function Wrapper({ children }: { children: React.ReactNode }) {
const content = <Provider store={store}>{children}</Provider>;
if (withNavigation) {
return <NavigationContainer>{content}</NavigationContainer>;
}
return content;
}

return {
store,
...render(ui, { wrapper: Wrapper, ...renderOptions }),
};
}
176 changes: 176 additions & 0 deletions __tests__/reducers/reducer.wallet.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
/**
* Unit tests for the wallet lifecycle reducer actions.
*
* Tests the full start → ready/failed cycle and the reset cycle,
* verifying that Redux state transitions match expectations.
*/
import { reducer } from '../../src/reducers/reducer';
import {
startWalletRequested,
startWalletSuccess,
startWalletFailed,
setWallet,
resetData,
resetWalletSuccess,
newToken,
setTokens,
updateSelectedToken,
} from '../../src/actions';
import { WALLET_STATUS } from '../../src/sagas/wallet';
import { DEFAULT_TOKEN, INITIAL_TOKENS } from '../../src/constants';

// Helper: get initial state from the reducer
const getInitialState = () => reducer(undefined, { type: '@@INIT' });

// ─── Wallet Start Lifecycle ────────────────────────────────────────────────
describe('wallet start lifecycle', () => {
it('starts in NOT_STARTED state', () => {
const state = getInitialState();
expect(state.walletStartState).toBe(WALLET_STATUS.NOT_STARTED);
});

it('transitions to LOADING on START_WALLET_REQUESTED', () => {
const state = getInitialState();
const next = reducer(state, startWalletRequested({ words: 'test', pin: '123456' }));
expect(next.walletStartState).toBe(WALLET_STATUS.LOADING);
});

it('transitions to READY on START_WALLET_SUCCESS', () => {
// Start from LOADING state
let state = reducer(getInitialState(), startWalletRequested({ words: 'test', pin: '123456' }));
state = reducer(state, startWalletSuccess());
expect(state.walletStartState).toBe(WALLET_STATUS.READY);
});

it('transitions to FAILED on START_WALLET_FAILED', () => {
let state = reducer(getInitialState(), startWalletRequested({ words: 'test', pin: '123456' }));
state = reducer(state, startWalletFailed());
expect(state.walletStartState).toBe(WALLET_STATUS.FAILED);
});

it('full lifecycle: NOT_STARTED → LOADING → READY', () => {
let state = getInitialState();
expect(state.walletStartState).toBe(WALLET_STATUS.NOT_STARTED);

state = reducer(state, startWalletRequested({ words: 'test', pin: '123456' }));
expect(state.walletStartState).toBe(WALLET_STATUS.LOADING);

state = reducer(state, startWalletSuccess());
expect(state.walletStartState).toBe(WALLET_STATUS.READY);
});
});

// ─── SET_WALLET ────────────────────────────────────────────────────────────
describe('SET_WALLET', () => {
it('sets wallet instance in state', () => {
const mockWallet = { id: 'test-wallet' };
const state = reducer(getInitialState(), setWallet(mockWallet));
expect(state.wallet).toBe(mockWallet);
});

it('can set wallet to null', () => {
const state = reducer(
{ ...getInitialState(), wallet: { id: 'existing' } },
setWallet(null),
);
expect(state.wallet).toBeNull();
});
});

// ─── Token Operations (populated during wallet start) ──────────────────────
describe('token operations', () => {
it('adds a new token via NEW_TOKEN', () => {
const token = { uid: 'token123', name: 'TestCoin', symbol: 'TST' };
const state = reducer(getInitialState(), newToken(token));
expect(state.tokens['token123']).toEqual(token);
// Initial default token should still be present
expect(state.tokens[DEFAULT_TOKEN.uid]).toBeDefined();
});

it('sets full token map via SET_TOKENS', () => {
const tokens = {
[DEFAULT_TOKEN.uid]: DEFAULT_TOKEN,
token123: { uid: 'token123', name: 'TestCoin', symbol: 'TST' },
};
const state = reducer(getInitialState(), setTokens(tokens));
expect(Object.keys(state.tokens)).toHaveLength(2);
expect(state.tokens['token123'].name).toBe('TestCoin');
});

it('resets selectedToken to DEFAULT_TOKEN if unregistered via SET_TOKENS', () => {
// Select a non-default token first
const customToken = { uid: 'custom', name: 'Custom', symbol: 'CUS' };
let state = reducer(getInitialState(), updateSelectedToken(customToken));
expect(state.selectedToken.uid).toBe('custom');

// Now set tokens without the custom one → should reset to default
state = reducer(state, setTokens({ [DEFAULT_TOKEN.uid]: DEFAULT_TOKEN }));
expect(state.selectedToken.uid).toBe(DEFAULT_TOKEN.uid);
});

it('keeps selectedToken if still present in SET_TOKENS', () => {
const customToken = { uid: 'custom', name: 'Custom', symbol: 'CUS' };
let state = reducer(getInitialState(), updateSelectedToken(customToken));
state = reducer(state, setTokens({
[DEFAULT_TOKEN.uid]: DEFAULT_TOKEN,
custom: customToken,
}));
expect(state.selectedToken.uid).toBe('custom');
});
});

// ─── Reset Cycle ───────────────────────────────────────────────────────────
describe('wallet reset', () => {
it('RESET_DATA returns full initial state', () => {
// Build up a modified state
let state = reducer(getInitialState(), startWalletRequested({ words: 'test', pin: '123456' }));
state = reducer(state, startWalletSuccess());
state = reducer(state, setWallet({ id: 'wallet' }));
state = reducer(state, newToken({ uid: 'token123', name: 'Test', symbol: 'TST' }));
expect(state.walletStartState).toBe(WALLET_STATUS.READY);

// Nuclear reset
const resetState = reducer(state, resetData());
expect(resetState.walletStartState).toBe(WALLET_STATUS.NOT_STARTED);
expect(resetState.wallet).toBeNull();
expect(resetState.tokens).toEqual(INITIAL_TOKENS);
expect(resetState.selectedToken).toEqual(DEFAULT_TOKEN);
expect(resetState.isOnline).toBe(false);
});

it('RESET_WALLET_SUCCESS resets state but preserves feature toggles', () => {
// Build up state with feature toggles set
let state = getInitialState();
// Simulate feature toggles being initialized
state = {
...state,
unleashClient: { mock: true },
featureTogglesInitialized: true,
featureToggles: { someFlag: true },
wallet: { id: 'wallet' },
walletStartState: WALLET_STATUS.READY,
};

const resetState = reducer(state, resetWalletSuccess());

// Wallet state should be reset
expect(resetState.walletStartState).toBe(WALLET_STATUS.NOT_STARTED);
expect(resetState.wallet).toBeNull();
expect(resetState.tokens).toEqual(INITIAL_TOKENS);

// Feature toggles should be preserved
expect(resetState.unleashClient).toEqual({ mock: true });
expect(resetState.featureTogglesInitialized).toBe(true);
expect(resetState.featureToggles).toEqual({ someFlag: true });
});

it('RESET_WALLET_SUCCESS clears tokens and balances', () => {
let state = getInitialState();
state = reducer(state, newToken({ uid: 'tok1', name: 'A', symbol: 'A' }));
state = { ...state, tokensBalance: { tok1: { data: { available: 100n } } } };

const resetState = reducer(state, resetWalletSuccess());
expect(resetState.tokens).toEqual(INITIAL_TOKENS);
expect(resetState.tokensBalance).toEqual({});
});
});
Loading
Loading