Skip to content
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

Integrate tanstack-query into typink #151

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions e2e/zombienet/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"@polkadot/keyring": "^13.3.1",
"@polkadot/types": "^15.4.1",
"@polkadot/util-crypto": "^13.3.1",
"@tanstack/react-query": "^5.66.0",
"dedot": "^0.6.1",
"happy-dom": "^15.11.7",
"typink": "workspace:*"
Expand Down
3 changes: 2 additions & 1 deletion e2e/zombienet/src/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { assert, deferred } from 'dedot/utils';
import { cryptoWaitReady } from '@polkadot/util-crypto';
import { KeyringPair } from '@polkadot/keyring/types';
import { TypeRegistry } from '@polkadot/types';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

await cryptoWaitReady();
export const KEYRING = new Keyring({ type: 'sr25519' });
Expand Down Expand Up @@ -48,7 +49,7 @@ export const Wrapper = ({ children, deployments = [] }: Props) => (
signer={mockSigner}
connectedAccount={{ address: ALICE }}
appName='Typink Test App'>
{children}
<QueryClientProvider client={new QueryClient()}>{children}</QueryClientProvider>
</TypinkProvider>
);

Expand Down
3 changes: 3 additions & 0 deletions packages/typink/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
"react": "^18.3.1",
"react-use": "^17.6.0"
},
"peerDependencies": {
"@tanstack/react-query": "^5.66.0"
},
"devDependencies": {
"@types/react": "^18.3.18"
},
Expand Down
5 changes: 5 additions & 0 deletions packages/typink/src/hooks/__tests__/test-utils.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { act } from '@testing-library/react';
import { Props } from '../../types.js';
import { TypinkEventsProvider } from '../../providers/index.js';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

export const waitForNextUpdate = async (then?: () => Promise<void>) => {
await act(async () => {
Expand All @@ -14,3 +15,7 @@ export const sleep = (ms: number = 0) => {
};

export const typinkEventsWrapper = ({ children }: Props) => <TypinkEventsProvider>{children}</TypinkEventsProvider>;

export const queryClientWrapper = ({ children }: Props) => (
<QueryClientProvider client={new QueryClient()}>{children}</QueryClientProvider>
);
203 changes: 110 additions & 93 deletions packages/typink/src/hooks/__tests__/useContractQuery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { act, renderHook, waitFor } from '@testing-library/react';
import { useContractQuery } from '../useContractQuery.js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { Contract } from 'dedot/contracts';
import { waitForNextUpdate } from './test-utils.js';
import { queryClientWrapper, waitForNextUpdate } from './test-utils.js';
import { useTypink } from '../useTypink.js';

// Mock the external dependencies
Expand Down Expand Up @@ -48,12 +48,14 @@ describe('useContractQuery', () => {
});

it('should return loading state initially', () => {
const { result } = renderHook(() =>
useContractQuery({
contract,
// @ts-ignore
fn: 'testFunction',
}),
const { result } = renderHook(
() =>
useContractQuery({
contract,
// @ts-ignore
fn: 'testFunction',
}),
{ wrapper: queryClientWrapper },
);

expect(result.current.isLoading).toBe(true);
Expand All @@ -63,14 +65,16 @@ describe('useContractQuery', () => {
contract.query.testFunction.mockResolvedValue({ data: 'test result' });

await act(async () => {
renderHook(() =>
useContractQuery({
contract,
// @ts-ignore
fn: 'testFunction',
args: ['arg1', 'arg2'],
options: { gasLimit: { refTime: 1000000n, proofSize: 1000000n } },
}),
renderHook(
() =>
useContractQuery({
contract,
// @ts-ignore
fn: 'testFunction',
args: ['arg1', 'arg2'],
options: { gasLimit: { refTime: 1000000n, proofSize: 1000000n } },
}),
{ wrapper: queryClientWrapper },
);
});

Expand All @@ -82,12 +86,14 @@ describe('useContractQuery', () => {
it('should update the result and loading state after query resolves', async () => {
contract.query.testFunction.mockResolvedValue({ data: 'test result' });

const { result } = renderHook(() =>
useContractQuery({
contract,
// @ts-ignore
fn: 'testFunction',
}),
const { result } = renderHook(
() =>
useContractQuery({
contract,
// @ts-ignore
fn: 'testFunction',
}),
{ wrapper: queryClientWrapper },
);

await act(async () => {
Expand All @@ -99,38 +105,38 @@ describe('useContractQuery', () => {
});

it('should not call query function if contract is undefined', async () => {
const { result } = renderHook(() =>
useContractQuery({
contract: undefined,
// @ts-ignore
fn: 'testFunction',
}),
const { result } = renderHook(
() =>
useContractQuery({
contract: undefined,
// @ts-ignore
fn: 'testFunction',
}),
{ wrapper: queryClientWrapper },
);

await waitForNextUpdate();

expect(result.current.isLoading).toBe(true);
expect(contract.query.testFunction).not.toHaveBeenCalled();
});

it('should refresh when refresh function is called', async () => {
contract.query.testFunction.mockResolvedValue({ data: 'test result' });

const { result } = renderHook(() =>
useContractQuery({
contract,
// @ts-ignore
fn: 'testFunction',
}),
const { result } = renderHook(
() =>
useContractQuery({
contract,
// @ts-ignore
fn: 'testFunction',
}),
{ wrapper: queryClientWrapper },
);

await waitForNextUpdate(async () => {
result.current.refresh();
});
await waitForNextUpdate();
result.current.refresh();

await waitForNextUpdate(async () => {
result.current.refresh();
});
await waitForNextUpdate();
result.current.refresh();

expect(contract.query.testFunction).toHaveBeenCalledTimes(3);
});
Expand All @@ -144,90 +150,99 @@ describe('useContractQuery', () => {
});
});

const { result } = renderHook(() =>
useContractQuery({
contract,
// @ts-ignore
fn: 'testFunction',
}),
const { result } = renderHook(
() =>
useContractQuery({
contract,
// @ts-ignore
fn: 'testFunction',
}),
{ wrapper: queryClientWrapper },
);

expect(result.current.isRefreshing).toBe(false);

await act(async () => {
result.current.refresh();
await waitFor(() => {
expect(result.current.isLoading).toBe(false);
});

expect(result.current.isRefreshing).toBe(true);
result.current.refresh();

await waitFor(() => {
expect(result.current.isRefreshing).toBe(true);
});

await waitFor(() => {
expect(result.current.isRefreshing).toBe(false);
expect(result.current.data).toBe('test result');
});
}),
it('should handle errors from the contract query', async () => {
const testError = new Error('Test error');
contract.query.testFunction.mockRejectedValue(testError);
});

it('should handle errors from the contract query', async () => {
const testError = new Error('Test error');
contract.query.testFunction.mockRejectedValue(testError);

const { result } = renderHook(() =>
const { result } = renderHook(
() =>
useContractQuery({
contract,
// @ts-ignore
fn: 'testFunction',
}),
);
{ wrapper: queryClientWrapper },
);

await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0));
});
expect(result.current.isLoading).toBe(true);

await waitFor(() => {
expect(result.current.isLoading).toBe(false);
expect(result.current.error).toBe(testError);
expect(result.current.data).toBeUndefined();
});
});

it('should reset error state on successful query after an error', async () => {
const testError = new Error('Test error');
contract.query.testFunction // prettier-end-here
.mockRejectedValueOnce(testError)
.mockResolvedValueOnce({ data: 'success after error' });

const { result } = renderHook(() =>
useContractQuery({
contract,
// @ts-ignore
fn: 'testFunction',
}),
const { result } = renderHook(
() =>
useContractQuery({
contract,
// @ts-ignore
fn: 'testFunction',
}),
{ wrapper: queryClientWrapper },
);

await waitForNextUpdate();
await waitFor(() => {
expect(result.current.isLoading).toBe(false);
expect(result.current.error).toBe(testError);
expect(result.current.data).toBeUndefined();
});

expect(result.current.isLoading).toBe(false);
expect(result.current.error).toBe(testError);
expect(result.current.data).toBeUndefined();
result.current.refresh();

await waitForNextUpdate(async () => {
result.current.refresh();
await waitFor(() => {
expect(result.current.isLoading).toBe(false);
expect(result.current.error).toBeNull();
expect(result.current.data).toEqual('success after error');
});

expect(result.current.isLoading).toBe(false);
expect(result.current.error).toBeUndefined();
expect(result.current.data).toEqual('success after error');
});

it('should maintain states if contract is undefined', async () => {
const { result } = renderHook(() =>
useContractQuery({
contract: undefined,
// @ts-ignore
fn: 'testFunction',
}),
const { result } = renderHook(
() =>
useContractQuery({
contract: undefined,
// @ts-ignore
fn: 'testFunction',
}),
{ wrapper: queryClientWrapper },
);

await waitForNextUpdate();

expect(result.current.isLoading).toBe(true);
expect(result.current.error).toBeUndefined();
expect(result.current.error).toBeNull();
expect(result.current.data).toBeUndefined();
});

Expand All @@ -246,13 +261,15 @@ describe('useContractQuery', () => {
});
});

const { result } = renderHook(() =>
useContractQuery({
contract,
// @ts-ignore
fn: 'message',
watch: true,
}),
const { result } = renderHook(
() =>
useContractQuery({
contract,
// @ts-ignore
fn: 'message',
watch: true,
}),
{ wrapper: queryClientWrapper },
);

await waitForNextUpdate();
Expand Down
Loading