Skip to content

Commit

Permalink
fix(tests): resolve transaction test failures by mocking dependencies…
Browse files Browse the repository at this point in the history
… properly
  • Loading branch information
davedumto committed Dec 17, 2024
1 parent 11368b2 commit 4368569
Showing 1 changed file with 47 additions and 111 deletions.
158 changes: 47 additions & 111 deletions frontend/test/services/transaction.test.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
import { connect } from 'starknetkit';
import { sendTransaction, closePosition, handleTransaction } from '../../src/services/transaction';
import { axiosInstance } from '../../src/utils/axios';
import { mockBackendUrl } from '../constants';
import { checkAndDeployContract } from '../../src/services/contract';

jest.mock('starknetkit');
jest.mock('../../src/utils/axios');
jest.mock('../../src/services/contract');

jest.mock('starknet', () => ({
CallData: class MockCallData {
constructor() {
return {
compile: jest.fn((fnName, args) => {
return Array.isArray(args) ? args : [args];
}),
};
compile(fnName, args) {
return Array.isArray(args) ? args : [args];
}
},
}));
Expand All @@ -33,103 +30,9 @@ describe('Transaction Functions', () => {
transaction_hash: mockTransactionHash,
}),
},
provider: {
getTransactionReceipt: jest.fn().mockResolvedValue({
status: 'ACCEPTED',
}),
},
};

connect.mockResolvedValue(mockStarknet);

process.env.REACT_APP_BACKEND_URL = mockBackendUrl;
});

afterEach(() => {
delete process.env.REACT_APP_BACKEND_URL;
});

describe('sendTransaction', () => {
const validLoopLiquidityData = {
pool_key: '0x123',
deposit_data: {
token: '0x456',
amount: '1000',
},
};

it('should successfully send a transaction', async () => {
const result = await sendTransaction(validLoopLiquidityData, mockContractAddress);

expect(connect).toHaveBeenCalled();
expect(result).toEqual({
loopTransaction: mockTransactionHash,
});
});

it('should throw error if wallet is not connected', async () => {
connect.mockResolvedValueOnce({ isConnected: false });

await expect(sendTransaction(validLoopLiquidityData, mockContractAddress)).rejects.toThrow(
'Wallet not connected'
);
});

it('should throw error if loop_liquidity_data is invalid', async () => {
const invalidData = { deposit_data: { token: '0x456' } };

await expect(sendTransaction(invalidData, mockContractAddress)).rejects.toThrow(
'Missing or invalid loop_liquidity_data fields'
);
});

it('should handle transaction errors correctly', async () => {
const mockError = new Error('Transaction failed');
connect.mockResolvedValueOnce({
isConnected: true,
account: {
execute: jest.fn().mockRejectedValue(mockError),
},
});

console.error = jest.fn();

await expect(sendTransaction(validLoopLiquidityData, mockContractAddress)).rejects.toThrow('Transaction failed');

expect(console.error).toHaveBeenCalledWith('Error sending transaction:', expect.any(Error));
});
});

describe('closePosition', () => {
const mockTransactionData = {
contract_address: mockContractAddress,
position_id: 1,
};

it('should successfully close a position', async () => {
await closePosition(mockTransactionData);

expect(connect).toHaveBeenCalled();
const mockStarknet = await connect();
expect(mockStarknet.account.execute).toHaveBeenCalledWith([
expect.objectContaining({
contractAddress: mockContractAddress,
entrypoint: 'close_position',
}),
]);
});

it('should handle close position errors', async () => {
const mockError = new Error('Close position failed');
connect.mockResolvedValueOnce({
isConnected: true,
account: {
execute: jest.fn().mockRejectedValue(mockError),
},
});

await expect(closePosition(mockTransactionData)).rejects.toThrow('Close position failed');
});
});

describe('handleTransaction', () => {
Expand All @@ -140,10 +43,7 @@ describe('Transaction Functions', () => {
const mockFormData = { position_id: 1 };

beforeEach(() => {
mockSetError.mockClear();
mockSetTokenAmount.mockClear();
mockSetLoading.mockClear();
mockSetSuccessful.mockClear();
jest.clearAllMocks();
});

it('should handle successful transaction flow', async () => {
Expand All @@ -157,35 +57,71 @@ describe('Transaction Functions', () => {
},
};

// Mock external calls
checkAndDeployContract.mockResolvedValueOnce();
axiosInstance.post.mockResolvedValueOnce({ data: mockTransactionData });
axiosInstance.get.mockResolvedValueOnce({
data: { status: 'open' },
});

await handleTransaction(mockWalletId, mockFormData, mockSetError, mockSetTokenAmount, mockSetLoading, mockSetSuccessful);
await handleTransaction(
mockWalletId,
mockFormData,
mockSetError,
mockSetTokenAmount,
mockSetLoading,
mockSetSuccessful
);

expect(mockSetLoading).toHaveBeenCalledWith(true);
expect(checkAndDeployContract).toHaveBeenCalledWith(mockWalletId);
expect(axiosInstance.post).toHaveBeenCalledWith('/api/create-position', mockFormData);
expect(axiosInstance.get).toHaveBeenCalledWith('/api/open-position', {
params: { position_id: mockTransactionData.position_id },
});
expect(mockSetTokenAmount).toHaveBeenCalledWith('');
expect(mockSetLoading).toHaveBeenCalledWith(false);
expect(mockSetError).toHaveBeenCalledWith('');
expect(mockSetSuccessful).not.toHaveBeenCalledWith(false);
});

it('should handle errors during deployment', async () => {
const mockError = new Error('Deployment failed');

checkAndDeployContract.mockRejectedValueOnce(mockError);

await handleTransaction(
mockWalletId,
mockFormData,
mockSetError,
mockSetTokenAmount,
mockSetLoading,
mockSetSuccessful
);

expect(mockSetError).toHaveBeenCalledWith('Error deploying contract. Please try again.');
expect(mockSetSuccessful).toHaveBeenCalledWith(false);
expect(mockSetLoading).toHaveBeenCalledWith(false);
});

it('should handle create position error', async () => {
const mockError = new Error('Create position failed');
axiosInstance.post.mockRejectedValueOnce(mockError);

console.error = jest.fn();
checkAndDeployContract.mockResolvedValueOnce();
axiosInstance.post.mockRejectedValueOnce(mockError);

await handleTransaction(mockWalletId, mockFormData, mockSetError, mockSetTokenAmount, mockSetLoading, mockSetSuccessful);
await handleTransaction(
mockWalletId,
mockFormData,
mockSetError,
mockSetTokenAmount,
mockSetLoading,
mockSetSuccessful
);

expect(mockSetError).toHaveBeenCalledWith('Failed to create position. Please try again.');
expect(console.error).toHaveBeenCalledWith('Failed to create position:', mockError);
expect(mockSetLoading).toHaveBeenCalledWith(false);
expect(mockSetSuccessful).toHaveBeenCalledWith(false);
expect(mockSetLoading).toHaveBeenCalledWith(false);
});
});
});

0 comments on commit 4368569

Please sign in to comment.