Skip to content

Commit

Permalink
chore: tests (#1031)
Browse files Browse the repository at this point in the history
  • Loading branch information
Zizzamia authored Aug 11, 2024
1 parent e797088 commit a0e2547
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 62 deletions.
22 changes: 7 additions & 15 deletions src/identity/utils/getAttestations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { base, opBNBTestnet } from 'viem/chains';
import { vi } from 'vitest';
import { getAttestationsByFilter } from '../../network/attestations';
import type { GetAttestationsOptions } from '../types';
import { easSupportedChains } from './easSupportedChains';
import { getAttestations } from './getAttestations';

vi.mock('../../network/attestations');
Expand All @@ -31,22 +30,17 @@ describe('getAttestations', () => {
vi.clearAllMocks();
});

it('throws an error for unsupported chains', () => {
try {
getAttestations(mockAddress, opBNBTestnet, mockOptions);
} catch (e) {
expect(e).toHaveProperty(
'message',
`Chain is not supported. Supported chains: ${Object.keys(
easSupportedChains,
).join(', ')}`,
);
}
it('should return and empty array for unsupported chains', async () => {
const result = await getAttestations(
mockAddress,
opBNBTestnet,
mockOptions,
);
expect(result).toEqual([]);
});

it('fetches attestations for supported chains', async () => {
(getAttestationsByFilter as vi.Mock).mockResolvedValue(mockAttestations);

const result = await getAttestations(mockAddress, base, mockOptions);
expect(result).toEqual(mockAttestations); // Replace [] with expected mockAttestations once implemented
});
Expand All @@ -66,9 +60,7 @@ describe('getAttestations', () => {
(getAttestationsByFilter as vi.Mock).mockRejectedValue(
new Error('Network error'),
);

const result = await getAttestations(mockAddress, base);

expect(result).toEqual([]);
});

Expand Down
14 changes: 5 additions & 9 deletions src/identity/utils/getAttestations.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Address, Chain } from 'viem';
import { getAttestationsByFilter } from '../../network/attestations';
import type { Attestation, GetAttestationsOptions } from '../types';
import { easSupportedChains, isChainSupported } from './easSupportedChains';
import { isChainSupported } from './easSupportedChains';

/**
* Fetches Ethereum Attestation Service (EAS) attestations for a given address and chain,
Expand All @@ -12,22 +12,18 @@ export async function getAttestations(
chain: Chain,
options?: GetAttestationsOptions,
): Promise<Attestation[]> {
if (!isChainSupported(chain)) {
console.log('Error in getAttestation: Chain is not supported');
return [];
}
try {
if (!isChainSupported(chain)) {
throw new Error(
`Chain is not supported. Supported chains: ${Object.keys(easSupportedChains).join(', ')}`,
);
}

// Default query filter values
const defaultQueryVariablesFilter = {
revoked: false,
expirationTime: Math.round(Date.now() / 1000),
limit: 10,
};

const queryVariablesFilter = { ...defaultQueryVariablesFilter, ...options };

return await getAttestationsByFilter(address, chain, queryVariablesFilter);
} catch (error) {
console.log(`Error in getAttestation: ${(error as Error).message}`);
Expand Down
48 changes: 14 additions & 34 deletions src/transaction/components/TransactionProvider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,12 @@ const TestComponent = () => {
<button type="button" onClick={context.onSubmit}>
Submit
</button>
<span data-testid="context-value">{JSON.stringify(context)}</span>
<span data-testid="context-value-errorMessage">
{context.errorMessage}
</span>
<span data-testid="context-value-isToastVisible">
{`${context.isToastVisible}`}
</span>
</div>
);
};
Expand Down Expand Up @@ -77,16 +82,13 @@ describe('TransactionProvider', () => {
statusWriteContracts: 'IDLE',
writeContractsAsync: writeContractsAsyncMock,
});

render(
<TransactionProvider address="0x123" contracts={[]} onError={() => {}}>
<TransactionProvider address="0x123" contracts={[]}>
<TestComponent />
</TransactionProvider>,
);

const button = screen.getByText('Submit');
fireEvent.click(button);

await waitFor(() => {
expect(writeContractsAsyncMock).toHaveBeenCalled();
});
Expand All @@ -97,25 +99,20 @@ describe('TransactionProvider', () => {
(useWaitForTransactionReceipt as ReturnType<typeof vi.fn>).mockReturnValue({
data: '123',
});

(useCallsStatus as ReturnType<typeof vi.fn>).mockReturnValue({
transactionHash: 'hash',
});

render(
<TransactionProvider
address="0x123"
contracts={[]}
onError={() => {}}
onSuccess={onSuccessMock}
>
<TestComponent />
</TransactionProvider>,
);

const button = screen.getByText('Submit');
fireEvent.click(button);

await waitFor(() => {
expect(onSuccessMock).toHaveBeenCalled();
});
Expand All @@ -129,20 +126,16 @@ describe('TransactionProvider', () => {
statusWriteContracts: 'IDLE',
writeContractsAsync: writeContractsAsyncMock,
});

render(
<TransactionProvider address="0x123" contracts={[]} onError={() => {}}>
<TransactionProvider address="0x123" contracts={[]}>
<TestComponent />
</TransactionProvider>,
);

const button = screen.getByText('Submit');
fireEvent.click(button);

await waitFor(() => {
const testComponent = screen.getByTestId('context-value');
const updatedContext = JSON.parse(testComponent.textContent || '{}');
expect(updatedContext.errorMessage).toBe(
const testComponent = screen.getByTestId('context-value-errorMessage');
expect(testComponent.textContent).toBe(
'Something went wrong. Please try again.',
);
});
Expand All @@ -153,21 +146,13 @@ describe('TransactionProvider', () => {
(useSwitchChain as ReturnType<typeof vi.fn>).mockReturnValue({
switchChainAsync: switchChainAsyncMock,
});

render(
<TransactionProvider
address="0x123"
chainId={2}
contracts={[]}
onError={() => {}}
>
<TransactionProvider address="0x123" chainId={2} contracts={[]}>
<TestComponent />
</TransactionProvider>,
);

const button = screen.getByText('Submit');
fireEvent.click(button);

await waitFor(() => {
expect(switchChainAsyncMock).toHaveBeenCalled();
});
Expand All @@ -178,20 +163,16 @@ describe('TransactionProvider', () => {
statusWriteContracts: 'IDLE',
writeContractsAsync: vi.fn().mockRejectedValue(new Error('Test error')),
});

render(
<TransactionProvider address="0x123" contracts={[]} onError={() => {}}>
<TransactionProvider address="0x123" contracts={[]}>
<TestComponent />
</TransactionProvider>,
);

const button = screen.getByText('Submit');
fireEvent.click(button);

await waitFor(() => {
const testComponent = screen.getByTestId('context-value');
const updatedContext = JSON.parse(testComponent.textContent || '{}');
expect(updatedContext.isToastVisible).toBe(true);
const testComponent = screen.getByTestId('context-value-isToastVisible');
expect(testComponent.textContent).toBe('true');
});
});
});
Expand All @@ -202,7 +183,6 @@ describe('useTransactionContext', () => {
useTransactionContext();
return null;
};

const consoleError = vi
.spyOn(console, 'error')
.mockImplementation(() => {}); // Suppress error logging
Expand Down
8 changes: 4 additions & 4 deletions vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ export default defineConfig({
],
reportOnFailure: true,
thresholds: {
statements: 99.28,
branches: 98.27,
functions: 94.47,
lines: 99.28,
statements: 99.33,
branches: 98.44,
functions: 96.69,
lines: 99.33,
},
},
environment: 'jsdom',
Expand Down

0 comments on commit a0e2547

Please sign in to comment.