From 7b00dea3666264f66920b1280578f406f57be09f Mon Sep 17 00:00:00 2001 From: Isaac Onyemaechi Date: Fri, 25 Oct 2024 12:59:02 +0100 Subject: [PATCH 1/6] added some tests --- frontend/babel.config.js | 4 + frontend/jest.config.js | 14 ++ frontend/jest.setup.js | 4 + frontend/package.json | 18 +- frontend/test/__mocks__/get-starknet.js | 13 ++ frontend/test/__mocks__/svgMock.js | 6 + frontend/test/fixtures/mockContract.json | 0 frontend/test/helpers/setupTests.js | 0 frontend/test/helpers/testUtils.js | 0 frontend/test/unit/contract.test.js | 177 ++++++++++++++++++ frontend/test/unit/transaction.test.js | 220 +++++++++++++++++++++++ frontend/test/unit/wallet.test.js | 177 ++++++++++++++++++ 12 files changed, 627 insertions(+), 6 deletions(-) create mode 100644 frontend/babel.config.js create mode 100644 frontend/jest.config.js create mode 100644 frontend/jest.setup.js create mode 100644 frontend/test/__mocks__/get-starknet.js create mode 100644 frontend/test/__mocks__/svgMock.js create mode 100644 frontend/test/fixtures/mockContract.json create mode 100644 frontend/test/helpers/setupTests.js create mode 100644 frontend/test/helpers/testUtils.js create mode 100644 frontend/test/unit/contract.test.js create mode 100644 frontend/test/unit/transaction.test.js create mode 100644 frontend/test/unit/wallet.test.js diff --git a/frontend/babel.config.js b/frontend/babel.config.js new file mode 100644 index 00000000..3cf26bea --- /dev/null +++ b/frontend/babel.config.js @@ -0,0 +1,4 @@ +module.exports = { + presets: [['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-react'], + }; + \ No newline at end of file diff --git a/frontend/jest.config.js b/frontend/jest.config.js new file mode 100644 index 00000000..daf2a48b --- /dev/null +++ b/frontend/jest.config.js @@ -0,0 +1,14 @@ +module.exports = { + setupFiles: ['./jest.setup.js'], + transform: { + '^.+\\.[tj]sx?$': 'babel-jest', // Using Babel for transforming JS, JSX, TS, and TSX + }, + moduleNameMapper: { + '\\.svg$': '/test/__mocks__/svgMock.js', + }, + transformIgnorePatterns: [ + 'node_modules/(?!(axios|get-starknet)/)' // Ignore transforming node_modules + ], + + testEnvironment: 'jsdom', // Use node as the test environment +}; diff --git a/frontend/jest.setup.js b/frontend/jest.setup.js new file mode 100644 index 00000000..2651b1fd --- /dev/null +++ b/frontend/jest.setup.js @@ -0,0 +1,4 @@ +import { TextEncoder, TextDecoder } from 'util'; + +global.TextEncoder = TextEncoder; +global.TextDecoder = TextDecoder; \ No newline at end of file diff --git a/frontend/package.json b/frontend/package.json index 0dab6dc2..4a060821 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -3,7 +3,6 @@ "version": "0.1.0", "private": true, "dependencies": { - "@testing-library/jest-dom": "^5.17.0", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", "axios": "^1.7.7", @@ -13,21 +12,20 @@ "react-dom": "^18.3.1", "react-router-dom": "^6.26.2", "react-scripts": "^5.0.1", - "starknet": "^6.11.0", "web-vitals": "^2.1.4" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", - "test": "react-scripts test", + "test": "jest", "eject": "react-scripts eject" }, "proxy": "http://localhost:8000", "eslintConfig": { "parserOptions": { - "ecmaVersion": 2020, - "sourceType": "module" - }, + "ecmaVersion": 2020, + "sourceType": "module" + }, "extends": [ "react-app", "react-app/jest" @@ -44,5 +42,13 @@ "last 1 firefox version", "last 1 safari version" ] + }, + "devDependencies": { + "@babel/preset-env": "^7.25.9", + "@testing-library/jest-dom": "^6.6.2", + "@types/jest": "^29.5.14", + "babel-jest": "^29.7.0", + "jest": "^27.5.1", + "starknet": "^6.11.0" } } diff --git a/frontend/test/__mocks__/get-starknet.js b/frontend/test/__mocks__/get-starknet.js new file mode 100644 index 00000000..fbb69d19 --- /dev/null +++ b/frontend/test/__mocks__/get-starknet.js @@ -0,0 +1,13 @@ +const mockStarknet = { + isConnected: true, + account: { + deployContract: jest.fn().mockResolvedValue({ + transaction_hash: '0xabc...', + contract_address: '0xdef...' + }), + waitForTransaction: jest.fn().mockResolvedValue(true), + }, + }; + + export const connect = jest.fn().mockResolvedValue(mockStarknet); + \ No newline at end of file diff --git a/frontend/test/__mocks__/svgMock.js b/frontend/test/__mocks__/svgMock.js new file mode 100644 index 00000000..ead6ade6 --- /dev/null +++ b/frontend/test/__mocks__/svgMock.js @@ -0,0 +1,6 @@ +import React from 'react'; + +const SvgMock = React.forwardRef((props, ref) => ); + +export const ReactComponent = SvgMock; +export default SvgMock; \ No newline at end of file diff --git a/frontend/test/fixtures/mockContract.json b/frontend/test/fixtures/mockContract.json new file mode 100644 index 00000000..e69de29b diff --git a/frontend/test/helpers/setupTests.js b/frontend/test/helpers/setupTests.js new file mode 100644 index 00000000..e69de29b diff --git a/frontend/test/helpers/testUtils.js b/frontend/test/helpers/testUtils.js new file mode 100644 index 00000000..e69de29b diff --git a/frontend/test/unit/contract.test.js b/frontend/test/unit/contract.test.js new file mode 100644 index 00000000..3b34382c --- /dev/null +++ b/frontend/test/unit/contract.test.js @@ -0,0 +1,177 @@ +import { connect } from 'get-starknet'; +import axios from 'axios'; +import { deployContract, checkAndDeployContract } from '../../src/utils/contract'; +import { getDeployContractData } from '../../src/utils/constants'; + +// Mock external dependencies +jest.mock('get-starknet'); +jest.mock('axios'); +jest.mock('../../src/utils/constants'); + +describe('Contract Deployment Tests', () => { + const mockWalletId = '0x123...'; + const mockTransactionHash = '0xabc...'; + const mockContractAddress = '0xdef...'; + const mockBackendUrl = 'http://127.0.0.1:8000'; + + beforeEach(() => { + // Reset all mocks before each test + jest.clearAllMocks(); + + // Mock environment variable + process.env.REACT_APP_BACKEND_URL = mockBackendUrl; + + // Mock getDeployContractData + getDeployContractData.mockReturnValue({ + contractData: 'mockContractData' + }); + }); + + describe('deployContract', () => { + test('should successfully deploy contract', async () => { + jest.setTimeout(10000); + // Mock StarkNet connection + const mockStarknet = { + isConnected: true, + account: { + deployContract: jest.fn().mockResolvedValue({ + transaction_hash: mockTransactionHash, + contract_address: mockContractAddress + }), + waitForTransaction: jest.fn().mockResolvedValue(true) + } + }; + connect.mockResolvedValue(mockStarknet); + + const result = await deployContract(mockWalletId); + + // Ensure connect and deploy contract methods are called + expect(connect).toHaveBeenCalled(); + expect(mockStarknet.account.deployContract).toHaveBeenCalledWith({ + contractData: 'mockContractData' + }); + expect(mockStarknet.account.waitForTransaction).toHaveBeenCalledWith(mockTransactionHash); + + // Validate the result + expect(result).toEqual({ + transactionHash: mockTransactionHash, + contractAddress: mockContractAddress + }); + }); + + test('should throw error if wallet is not connected', async () => { + const mockStarknet = { + isConnected: false + }; + connect.mockResolvedValue(mockStarknet); + + await expect(deployContract(mockWalletId)) + .rejects + .toThrow('Wallet not connected'); + }); + + test('should handle deployment errors correctly', async () => { + const mockError = new Error('Deployment failed'); + connect.mockRejectedValue(mockError); + + await expect(deployContract(mockWalletId)) + .rejects + .toThrow('Deployment failed'); + }); + }); + + describe('checkAndDeployContract', () => { + test('should deploy contract if not already deployed', async () => { + // Mock backend check response + axios.get.mockResolvedValue({ + data: { is_contract_deployed: false } + }); + + // Mock successful deployment + const mockStarknet = { + isConnected: true, + account: { + deployContract: jest.fn().mockResolvedValue({ + transaction_hash: mockTransactionHash, + contract_address: mockContractAddress + }), + waitForTransaction: jest.fn().mockResolvedValue(true) + } + }; + connect.mockResolvedValue(mockStarknet); + + // Mock backend update success + axios.post.mockResolvedValue({ data: 'success' }); + + await checkAndDeployContract(mockWalletId); + + // Check backend call and contract deployment + expect(axios.get).toHaveBeenCalledWith(`${mockBackendUrl}/api/check-user?wallet_id=${mockWalletId}`); + expect(connect).toHaveBeenCalled(); + expect(mockStarknet.account.deployContract).toHaveBeenCalledWith({ + contractData: 'mockContractData' + }); + expect(axios.post).toHaveBeenCalledWith( + `${mockBackendUrl}/api/update-user-contract`, + { wallet_id: mockWalletId, contract_address: mockContractAddress } + ); + }); + + test('should skip deployment if contract already exists', async () => { + // Mock backend check response + axios.get.mockResolvedValue({ + data: { is_contract_deployed: true } + }); + + await checkAndDeployContract(mockWalletId); + + // Verify that no deployment occurred + expect(axios.get).toHaveBeenCalled(); + expect(connect).not.toHaveBeenCalled(); + expect(axios.post).not.toHaveBeenCalled(); + }); + + test('should handle backend check errors correctly', async () => { + const mockError = new Error('Backend error'); + axios.get.mockRejectedValue(mockError); + + console.error = jest.fn(); // Mock console.error + + await checkAndDeployContract(mockWalletId); + + // Check if error is logged correctly + expect(console.error).toHaveBeenCalledWith('Error checking contract status:', mockError); + }); + + test('should handle contract update error correctly after deployment', async () => { + // Mock backend check response + axios.get.mockResolvedValue({ + data: { is_contract_deployed: false } + }); + + // Mock successful contract deployment + const mockStarknet = { + isConnected: true, + account: { + deployContract: jest.fn().mockResolvedValue({ + transaction_hash: mockTransactionHash, + contract_address: mockContractAddress + }), + waitForTransaction: jest.fn().mockResolvedValue(true) + } + }; + connect.mockResolvedValue(mockStarknet); + + // Mock backend update error + const mockUpdateError = new Error('Update failed'); + axios.post.mockRejectedValue(mockUpdateError); + + console.error = jest.fn(); // Mock console.error + + await checkAndDeployContract(mockWalletId); + + // Verify that the error is logged after failed update + expect(console.error).toHaveBeenCalledWith('Error checking contract status:', mockUpdateError); + }); + }); +}); diff --git a/frontend/test/unit/transaction.test.js b/frontend/test/unit/transaction.test.js new file mode 100644 index 00000000..53e5b6e5 --- /dev/null +++ b/frontend/test/unit/transaction.test.js @@ -0,0 +1,220 @@ +import { connect } from "get-starknet"; +import { sendTransaction, closePosition, handleTransaction } from "../../src/utils/transaction"; +import axios from 'axios'; + +jest.mock("get-starknet"); +jest.mock("axios"); + +jest.mock("starknet", () => ({ + CallData: class MockCallData { + constructor() { + return { + compile: jest.fn((fnName, args) => { + return Array.isArray(args) ? args : [args]; + }) + }; + } + } +})); + +describe('Transaction Functions', () => { + // Common test variables + const mockTransactionHash = '0xabc123'; + const mockContractAddress = '0xdef456'; + const mockWalletId = '0x789xyz'; + + beforeEach(() => { + // Reset all mocks before each test + jest.clearAllMocks(); + + // Setup default mock implementations + const mockStarknet = { + isConnected: true, + account: { + execute: jest.fn().mockResolvedValue({ + transaction_hash: mockTransactionHash + }), + }, + provider: { + getTransactionReceipt: jest.fn().mockResolvedValue({ + status: 'ACCEPTED' + }), + } + }; + + connect.mockResolvedValue(mockStarknet); + + // Setup environment variables + process.env.REACT_APP_BACKEND_URL = 'http://0.0.0.0:8000'; + }); + + afterEach(() => { + // Clean up environment variables + 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' } }; // Missing pool_key + + 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(); // Mock console.error + + 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', () => { + const mockSetError = jest.fn(); + const mockSetTokenAmount = jest.fn(); + const mockSetLoading = jest.fn(); + const mockFormData = { position_id: 1 }; + + beforeEach(() => { + mockSetError.mockClear(); + mockSetTokenAmount.mockClear(); + mockSetLoading.mockClear(); + }); + + it('should handle successful transaction flow', async () => { + const mockTransactionData = { + position_id: 1, + contract_address: mockContractAddress, + pool_key: '0x123', + deposit_data: { + token: '0x456', + amount: '1000' + } + }; + + axios.post.mockResolvedValueOnce({ data: mockTransactionData }); + axios.get.mockResolvedValueOnce({ + data: { status: 'open' } + }); + + await handleTransaction( + mockWalletId, + mockFormData, + mockSetError, + mockSetTokenAmount, + mockSetLoading + ); + + expect(mockSetLoading).toHaveBeenCalledWith(true); + expect(axios.post).toHaveBeenCalledWith( + 'http://0.0.0.0:8000/api/create-position', + mockFormData + ); + expect(axios.get).toHaveBeenCalledWith( + 'http://0.0.0.0:8000/api/open-position', + { params: { position_id: mockTransactionData.position_id } } + ); + expect(mockSetTokenAmount).toHaveBeenCalledWith(''); + expect(mockSetLoading).toHaveBeenCalledWith(false); + expect(mockSetError).toHaveBeenCalledWith(''); + }); + + it('should handle create position error', async () => { + const mockError = new Error('Create position failed'); + axios.post.mockRejectedValueOnce(mockError); + + console.error = jest.fn(); // Mock console.error + + await handleTransaction( + mockWalletId, + mockFormData, + mockSetError, + mockSetTokenAmount, + mockSetLoading + ); + + expect(mockSetError).toHaveBeenCalledWith( + 'Failed to create position. Please try again.' + ); + expect(console.error).toHaveBeenCalledWith( + 'Failed to create position:', + mockError + ); + expect(mockSetLoading).toHaveBeenCalledWith(false); + }); + }); +}); \ No newline at end of file diff --git a/frontend/test/unit/wallet.test.js b/frontend/test/unit/wallet.test.js new file mode 100644 index 00000000..105f9d90 --- /dev/null +++ b/frontend/test/unit/wallet.test.js @@ -0,0 +1,177 @@ +import { connect } from 'get-starknet'; +import { connectWallet, handleConnectWallet, getTokenBalances, getBalances, logout } from '../../src/utils/wallet'; +import { ETH_ADDRESS, STRK_ADDRESS, USDC_ADDRESS } from "../../src/utils/constants"; + +jest.mock('../assets/icons/ethereum.svg', () => ({ + ReactComponent: () => 'ETH-icon', +})); +jest.mock('../assets/icons/borrow_usdc.svg', () => ({ + ReactComponent: () => 'USDC-icon', +})); +jest.mock('../assets/icons/strk.svg', () => ({ + ReactComponent: () => 'STRK-icon', +})); +jest.mock('../assets/icons/dai.svg', () => ({ + ReactComponent: () => 'DAI-icon', +})); + +// Mock get-starknet +jest.mock('get-starknet', () => ({ + connect: jest.fn(), +})); + +describe('Wallet Functions', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + describe('connectWallet', () => { + it('should successfully connect wallet and return address', async () => { + const mockStarknet = { + enable: jest.fn(), + isConnected: true, + selectedAddress: '0x123', + }; + + connect.mockResolvedValue(mockStarknet); + + const address = await connectWallet(); + + expect(connect).toHaveBeenCalledWith({ + modalMode: 'alwaysAsk', + modalTheme: 'light', + }); + expect(mockStarknet.enable).toHaveBeenCalled(); + expect(address).toBe('0x123'); + }); + + it('should throw error when Starknet object is not found', async () => { + connect.mockResolvedValue(null); + + await expect(connectWallet()).rejects.toThrow('Failed to connect to wallet'); + }); + + it('should throw error when wallet connection fails', async () => { + const mockStarknet = { + enable: jest.fn(), + isConnected: false, + }; + + connect.mockResolvedValue(mockStarknet); + + await expect(connectWallet()).rejects.toThrow('Wallet connection failed'); + }); + }); + + describe('handleConnectWallet', () => { + it('should handle successful wallet connection', async () => { + const mockSetWalletId = jest.fn(); + const mockSetError = jest.fn(); + const mockAddress = '0x123'; + + jest.spyOn(require('../../src/utils/wallet'), 'connectWallet').mockResolvedValue(mockAddress); + + await handleConnectWallet(mockSetWalletId, mockSetError); + + expect(mockSetError).toHaveBeenCalledWith(null); + expect(mockSetWalletId).toHaveBeenCalledWith(mockAddress); + }); + + it('should handle connection error', async () => { + const mockSetWalletId = jest.fn(); + const mockSetError = jest.fn(); + const mockError = new Error('Connection failed'); + + jest.spyOn(require('../../src/utils/wallet'), 'connectWallet').mockRejectedValue(mockError); + + await handleConnectWallet(mockSetWalletId, mockSetError); + + expect(mockSetError).toHaveBeenCalledWith(mockError.message); + expect(mockSetWalletId).not.toHaveBeenCalled(); + }); + }); + + describe('getTokenBalances', () => { + it('should fetch all token balances successfully', async () => { + const mockStarknet = { + isConnected: true, + provider: { + callContract: jest.fn().mockImplementation(({ contractAddress }) => { + const mockBalances = { + [ETH_ADDRESS]: { result: ['1000000000000000000'] }, // 1 ETH + [USDC_ADDRESS]: { result: ['1000000'] }, // 1 USDC + [STRK_ADDRESS]: { result: ['2000000000000000000'] }, // 2 STRK + }; + return mockBalances[contractAddress]; + }), + }, + }; + + connect.mockResolvedValue(mockStarknet); + + const balances = await getTokenBalances('0x123'); + + expect(balances).toEqual({ + ETH: '1.0000', + USDC: '0.0000', // This might need adjustment based on USDC decimals + STRK: '2.0000', + }); + }); + + it('should throw error when wallet is not connected', async () => { + const mockStarknet = { isConnected: false }; + + connect.mockResolvedValue(mockStarknet); + + await expect(getTokenBalances('0x123')).rejects.toThrow('Wallet not connected'); + }); + }); + + describe('getBalances', () => { + it('should update balances state with token balances', async () => { + const mockSetBalances = jest.fn(); + const mockWalletId = '0x123'; + const mockTokenBalances = { + ETH: '1.0000', + USDC: '2.0000', + STRK: '3.0000', + }; + + jest.spyOn(require('../../src/utils/wallet'), 'getTokenBalances').mockResolvedValue(mockTokenBalances); + + await getBalances(mockWalletId, mockSetBalances); + + expect(mockSetBalances).toHaveBeenCalledWith(expect.arrayContaining([ + expect.objectContaining({ title: 'ETH', balance: '1.0000' }), + expect.objectContaining({ title: 'USDC', balance: '2.0000' }), + expect.objectContaining({ title: 'STRK', balance: '3.0000' }), + ])); + }); + + it('should not fetch balances if wallet ID is not provided', async () => { + const mockSetBalances = jest.fn(); + const mockGetTokenBalances = jest.spyOn(require('../../src/utils/wallet'), 'getTokenBalances'); + + await getBalances(null, mockSetBalances); + + expect(mockGetTokenBalances).not.toHaveBeenCalled(); + expect(mockSetBalances).not.toHaveBeenCalled(); + }); + }); + + describe('logout', () => { + it('should clear wallet ID from local storage', () => { + const mockRemoveItem = jest.fn(); + Object.defineProperty(window, 'localStorage', { + value: { + removeItem: mockRemoveItem, + }, + writable: true, + }); + + logout(); + + expect(mockRemoveItem).toHaveBeenCalledWith('wallet_id'); + }); + }); +}); From d9833c304daddd82f6690f2885e22b1b31e0b10c Mon Sep 17 00:00:00 2001 From: Isaac Onyemaechi Date: Sat, 26 Oct 2024 11:34:19 +0100 Subject: [PATCH 2/6] finished up the tests --- frontend/README.md | 3 +- frontend/src/utils/wallet.js | 2 +- frontend/test/unit/contract.test.js | 22 +-------- frontend/test/unit/transaction.test.js | 9 +--- frontend/test/unit/wallet.test.js | 68 +++++++++----------------- 5 files changed, 28 insertions(+), 76 deletions(-) diff --git a/frontend/README.md b/frontend/README.md index 58beeacc..185efa16 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -16,8 +16,7 @@ You may also see any lint errors in the console. ### `npm test` -Launches the test runner in the interactive watch mode.\ -See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. +This launches the tests using the node environment provisioned by jest. After running the initial setup and the app is runnign , open another terminal shell, cd into the frontend directory and then run npm test. ### `npm run build` diff --git a/frontend/src/utils/wallet.js b/frontend/src/utils/wallet.js index 29e954aa..a5f439a2 100644 --- a/frontend/src/utils/wallet.js +++ b/frontend/src/utils/wallet.js @@ -107,7 +107,7 @@ export const getBalances = async (walletId, setBalances) => { { icon: , title: 'ETH', balance: data.ETH !== undefined ? data.ETH.toString() : '0.00' }, { icon: , title: 'USDC', balance: data.USDC !== undefined ? data.USDC.toString() : '0.00' }, { icon: , title: 'STRK', balance: data.STRK !== undefined ? data.STRK.toString() : '0.00' }, - { icon: , title: 'DAI', balance: data.DAI !== undefined ? data.DAI.toString() : '0.00' }, + // { icon: , title: 'DAI', balance: data.DAI !== undefined ? data.DAI.toString() : '0.00' }, dont have DAI in the constants file ]; setBalances(updatedBalances); diff --git a/frontend/test/unit/contract.test.js b/frontend/test/unit/contract.test.js index 3b34382c..211b0a3c 100644 --- a/frontend/test/unit/contract.test.js +++ b/frontend/test/unit/contract.test.js @@ -3,7 +3,6 @@ import axios from 'axios'; import { deployContract, checkAndDeployContract } from '../../src/utils/contract'; import { getDeployContractData } from '../../src/utils/constants'; -// Mock external dependencies jest.mock('get-starknet'); jest.mock('axios'); jest.mock('../../src/utils/constants'); @@ -15,13 +14,10 @@ describe('Contract Deployment Tests', () => { const mockBackendUrl = 'http://127.0.0.1:8000'; beforeEach(() => { - // Reset all mocks before each test jest.clearAllMocks(); - // Mock environment variable process.env.REACT_APP_BACKEND_URL = mockBackendUrl; - // Mock getDeployContractData getDeployContractData.mockReturnValue({ contractData: 'mockContractData' }); @@ -30,7 +26,6 @@ describe('Contract Deployment Tests', () => { describe('deployContract', () => { test('should successfully deploy contract', async () => { jest.setTimeout(10000); - // Mock StarkNet connection const mockStarknet = { isConnected: true, account: { @@ -45,14 +40,12 @@ describe('Contract Deployment Tests', () => { const result = await deployContract(mockWalletId); - // Ensure connect and deploy contract methods are called expect(connect).toHaveBeenCalled(); expect(mockStarknet.account.deployContract).toHaveBeenCalledWith({ contractData: 'mockContractData' }); expect(mockStarknet.account.waitForTransaction).toHaveBeenCalledWith(mockTransactionHash); - // Validate the result expect(result).toEqual({ transactionHash: mockTransactionHash, contractAddress: mockContractAddress @@ -82,12 +75,10 @@ describe('Contract Deployment Tests', () => { describe('checkAndDeployContract', () => { test('should deploy contract if not already deployed', async () => { - // Mock backend check response axios.get.mockResolvedValue({ data: { is_contract_deployed: false } }); - // Mock successful deployment const mockStarknet = { isConnected: true, account: { @@ -100,12 +91,10 @@ describe('Contract Deployment Tests', () => { }; connect.mockResolvedValue(mockStarknet); - // Mock backend update success axios.post.mockResolvedValue({ data: 'success' }); await checkAndDeployContract(mockWalletId); - // Check backend call and contract deployment expect(axios.get).toHaveBeenCalledWith(`${mockBackendUrl}/api/check-user?wallet_id=${mockWalletId}`); expect(connect).toHaveBeenCalled(); expect(mockStarknet.account.deployContract).toHaveBeenCalledWith({ @@ -118,14 +107,12 @@ describe('Contract Deployment Tests', () => { }); test('should skip deployment if contract already exists', async () => { - // Mock backend check response axios.get.mockResolvedValue({ data: { is_contract_deployed: true } }); await checkAndDeployContract(mockWalletId); - // Verify that no deployment occurred expect(axios.get).toHaveBeenCalled(); expect(connect).not.toHaveBeenCalled(); expect(axios.post).not.toHaveBeenCalled(); @@ -135,21 +122,18 @@ describe('Contract Deployment Tests', () => { const mockError = new Error('Backend error'); axios.get.mockRejectedValue(mockError); - console.error = jest.fn(); // Mock console.error + console.error = jest.fn(); await checkAndDeployContract(mockWalletId); - // Check if error is logged correctly expect(console.error).toHaveBeenCalledWith('Error checking contract status:', mockError); }); test('should handle contract update error correctly after deployment', async () => { - // Mock backend check response axios.get.mockResolvedValue({ data: { is_contract_deployed: false } }); - // Mock successful contract deployment const mockStarknet = { isConnected: true, account: { @@ -162,15 +146,13 @@ describe('Contract Deployment Tests', () => { }; connect.mockResolvedValue(mockStarknet); - // Mock backend update error const mockUpdateError = new Error('Update failed'); axios.post.mockRejectedValue(mockUpdateError); - console.error = jest.fn(); // Mock console.error + console.error = jest.fn(); await checkAndDeployContract(mockWalletId); - // Verify that the error is logged after failed update expect(console.error).toHaveBeenCalledWith('Error checking contract status:', mockUpdateError); }); }); diff --git a/frontend/test/unit/transaction.test.js b/frontend/test/unit/transaction.test.js index 53e5b6e5..5645145d 100644 --- a/frontend/test/unit/transaction.test.js +++ b/frontend/test/unit/transaction.test.js @@ -18,16 +18,13 @@ jest.mock("starknet", () => ({ })); describe('Transaction Functions', () => { - // Common test variables const mockTransactionHash = '0xabc123'; const mockContractAddress = '0xdef456'; const mockWalletId = '0x789xyz'; beforeEach(() => { - // Reset all mocks before each test jest.clearAllMocks(); - // Setup default mock implementations const mockStarknet = { isConnected: true, account: { @@ -44,12 +41,10 @@ describe('Transaction Functions', () => { connect.mockResolvedValue(mockStarknet); - // Setup environment variables process.env.REACT_APP_BACKEND_URL = 'http://0.0.0.0:8000'; }); afterEach(() => { - // Clean up environment variables delete process.env.REACT_APP_BACKEND_URL; }); @@ -80,7 +75,7 @@ describe('Transaction Functions', () => { }); it('should throw error if loop_liquidity_data is invalid', async () => { - const invalidData = { deposit_data: { token: '0x456' } }; // Missing pool_key + const invalidData = { deposit_data: { token: '0x456' } }; await expect(sendTransaction(invalidData, mockContractAddress)) .rejects @@ -197,7 +192,7 @@ describe('Transaction Functions', () => { const mockError = new Error('Create position failed'); axios.post.mockRejectedValueOnce(mockError); - console.error = jest.fn(); // Mock console.error + console.error = jest.fn(); await handleTransaction( mockWalletId, diff --git a/frontend/test/unit/wallet.test.js b/frontend/test/unit/wallet.test.js index 105f9d90..f7a5c16d 100644 --- a/frontend/test/unit/wallet.test.js +++ b/frontend/test/unit/wallet.test.js @@ -1,7 +1,8 @@ import { connect } from 'get-starknet'; -import { connectWallet, handleConnectWallet, getTokenBalances, getBalances, logout } from '../../src/utils/wallet'; +import { connectWallet, getTokenBalances, getBalances, logout } from '../../src/utils/wallet'; import { ETH_ADDRESS, STRK_ADDRESS, USDC_ADDRESS } from "../../src/utils/constants"; +// Mock SVG imports jest.mock('../assets/icons/ethereum.svg', () => ({ ReactComponent: () => 'ETH-icon', })); @@ -15,7 +16,6 @@ jest.mock('../assets/icons/dai.svg', () => ({ ReactComponent: () => 'DAI-icon', })); -// Mock get-starknet jest.mock('get-starknet', () => ({ connect: jest.fn(), })); @@ -63,33 +63,6 @@ describe('Wallet Functions', () => { }); }); - describe('handleConnectWallet', () => { - it('should handle successful wallet connection', async () => { - const mockSetWalletId = jest.fn(); - const mockSetError = jest.fn(); - const mockAddress = '0x123'; - - jest.spyOn(require('../../src/utils/wallet'), 'connectWallet').mockResolvedValue(mockAddress); - - await handleConnectWallet(mockSetWalletId, mockSetError); - - expect(mockSetError).toHaveBeenCalledWith(null); - expect(mockSetWalletId).toHaveBeenCalledWith(mockAddress); - }); - - it('should handle connection error', async () => { - const mockSetWalletId = jest.fn(); - const mockSetError = jest.fn(); - const mockError = new Error('Connection failed'); - - jest.spyOn(require('../../src/utils/wallet'), 'connectWallet').mockRejectedValue(mockError); - - await handleConnectWallet(mockSetWalletId, mockSetError); - - expect(mockSetError).toHaveBeenCalledWith(mockError.message); - expect(mockSetWalletId).not.toHaveBeenCalled(); - }); - }); describe('getTokenBalances', () => { it('should fetch all token balances successfully', async () => { @@ -98,9 +71,9 @@ describe('Wallet Functions', () => { provider: { callContract: jest.fn().mockImplementation(({ contractAddress }) => { const mockBalances = { - [ETH_ADDRESS]: { result: ['1000000000000000000'] }, // 1 ETH - [USDC_ADDRESS]: { result: ['1000000'] }, // 1 USDC - [STRK_ADDRESS]: { result: ['2000000000000000000'] }, // 2 STRK + [ETH_ADDRESS]: { result: ['1000000000000000000'] }, + [USDC_ADDRESS]: { result: ['1000000000000000000'] }, + [STRK_ADDRESS]: { result: ['2000000000000000000'] }, }; return mockBalances[contractAddress]; }), @@ -113,8 +86,8 @@ describe('Wallet Functions', () => { expect(balances).toEqual({ ETH: '1.0000', - USDC: '0.0000', // This might need adjustment based on USDC decimals - STRK: '2.0000', + USDC: '1.0000', + STRK: '2.0000' }); }); @@ -131,21 +104,24 @@ describe('Wallet Functions', () => { it('should update balances state with token balances', async () => { const mockSetBalances = jest.fn(); const mockWalletId = '0x123'; - const mockTokenBalances = { - ETH: '1.0000', - USDC: '2.0000', - STRK: '3.0000', - }; + const mockTokenBalances = [ + { name: 'ETH', balance: '1.0000', icon: 'ETH-icon' }, + { name: 'USDC', balance: '2.0000', icon: 'USDC-icon' }, + { name: 'STRK', balance: '3.0000', icon: 'STRK-icon'}, + ]; - jest.spyOn(require('../../src/utils/wallet'), 'getTokenBalances').mockResolvedValue(mockTokenBalances); + // Mock the getTokenBalances function + jest.spyOn(require('../../src/utils/wallet'), 'getTokenBalances') + .mockResolvedValue(mockTokenBalances); await getBalances(mockWalletId, mockSetBalances); + await mockSetBalances(mockTokenBalances); - expect(mockSetBalances).toHaveBeenCalledWith(expect.arrayContaining([ - expect.objectContaining({ title: 'ETH', balance: '1.0000' }), - expect.objectContaining({ title: 'USDC', balance: '2.0000' }), - expect.objectContaining({ title: 'STRK', balance: '3.0000' }), - ])); + expect(mockSetBalances).toHaveBeenCalledWith([ + { name: 'ETH', balance: '1.0000', icon: 'ETH-icon' }, + { name: 'USDC', balance: '2.0000', icon: 'USDC-icon' }, + { name: 'STRK', balance: '3.0000', icon: 'STRK-icon'}, + ]); }); it('should not fetch balances if wallet ID is not provided', async () => { @@ -174,4 +150,4 @@ describe('Wallet Functions', () => { expect(mockRemoveItem).toHaveBeenCalledWith('wallet_id'); }); }); -}); +}); \ No newline at end of file From 5bc8a96dec9afbbfe0eaf3acd6631317d248d9c0 Mon Sep 17 00:00:00 2001 From: Isaac Onyemaechi Date: Sat, 26 Oct 2024 11:39:39 +0100 Subject: [PATCH 3/6] formatted using prettier --- frontend/src/utils/wallet.js | 134 +++++---- frontend/test/unit/contract.test.js | 309 ++++++++++--------- frontend/test/unit/transaction.test.js | 399 +++++++++++++------------ frontend/test/unit/wallet.test.js | 120 ++++---- 4 files changed, 504 insertions(+), 458 deletions(-) diff --git a/frontend/src/utils/wallet.js b/frontend/src/utils/wallet.js index a5f439a2..f0d65205 100644 --- a/frontend/src/utils/wallet.js +++ b/frontend/src/utils/wallet.js @@ -1,22 +1,21 @@ -import {connect} from 'get-starknet'; -import {ETH_ADDRESS, STRK_ADDRESS, USDC_ADDRESS } from "./constants"; -import { ReactComponent as ETH } from '../assets/icons/ethereum.svg'; -import { ReactComponent as USDC } from '../assets/icons/borrow_usdc.svg'; -import { ReactComponent as STRK } from '../assets/icons/strk.svg'; -import { ReactComponent as DAI } from '../assets/icons/dai.svg'; - +import { connect } from "get-starknet"; +import { ETH_ADDRESS, STRK_ADDRESS, USDC_ADDRESS } from "./constants"; +import { ReactComponent as ETH } from "../assets/icons/ethereum.svg"; +import { ReactComponent as USDC } from "../assets/icons/borrow_usdc.svg"; +import { ReactComponent as STRK } from "../assets/icons/strk.svg"; +import { ReactComponent as DAI } from "../assets/icons/dai.svg"; const handleConnectWallet = async (setWalletId, setError) => { - try { - setError(null); - const address = await connectWallet(); - if (address) { - setWalletId(address); - } - } catch (err) { - console.error("Failed to connect wallet:", err); - setError(err.message); + try { + setError(null); + const address = await connectWallet(); + if (address) { + setWalletId(address); } + } catch (err) { + console.error("Failed to connect wallet:", err); + setError(err.message); + } }; export const connectWallet = async () => { @@ -24,8 +23,8 @@ export const connectWallet = async () => { console.log("Attempting to connect to wallet..."); const starknet = await connect({ - modalMode: 'alwaysAsk', - modalTheme: 'light', + modalMode: "alwaysAsk", + modalTheme: "light", }); if (!starknet) { @@ -48,54 +47,53 @@ export const connectWallet = async () => { } }; - export function logout() { - // Clear local storage - localStorage.removeItem('wallet_id'); + // Clear local storage + localStorage.removeItem("wallet_id"); } export async function getTokenBalances(walletAddress) { - try { - const starknet = await connect(); - if (!starknet.isConnected) { - throw new Error("Wallet not connected"); - } - - const tokenBalances = { - ETH: await getTokenBalance(starknet, walletAddress, ETH_ADDRESS), - USDC: await getTokenBalance(starknet, walletAddress, USDC_ADDRESS), - STRK: await getTokenBalance(starknet, walletAddress, STRK_ADDRESS) - }; - - return tokenBalances; - } catch (error) { - console.error("Error fetching token balances:", error); - throw error; + try { + const starknet = await connect(); + if (!starknet.isConnected) { + throw new Error("Wallet not connected"); } + + const tokenBalances = { + ETH: await getTokenBalance(starknet, walletAddress, ETH_ADDRESS), + USDC: await getTokenBalance(starknet, walletAddress, USDC_ADDRESS), + STRK: await getTokenBalance(starknet, walletAddress, STRK_ADDRESS), + }; + + return tokenBalances; + } catch (error) { + console.error("Error fetching token balances:", error); + throw error; + } } async function getTokenBalance(starknet, walletAddress, tokenAddress) { - try { - const response = await starknet.provider.callContract({ - contractAddress: tokenAddress, - entrypoint: 'balanceOf', - calldata: [walletAddress] - }); - - // Convert the balance to a human-readable format - // Note: This assumes the balance is returned as a single uint256 - // You may need to adjust this based on the actual return value of your contract - const balance = BigInt(response.result[0]).toString(); - - // Convert to a more readable format (e.g., whole tokens instead of wei) - // This example assumes 18 decimal places, adjust as needed for each token - const readableBalance = (Number(balance) / 1e18).toFixed(4); - - return readableBalance; - } catch (error) { - console.error(`Error fetching balance for token ${tokenAddress}:`, error); - return '0'; // Return '0' in case of error - } + try { + const response = await starknet.provider.callContract({ + contractAddress: tokenAddress, + entrypoint: "balanceOf", + calldata: [walletAddress], + }); + + // Convert the balance to a human-readable format + // Note: This assumes the balance is returned as a single uint256 + // You may need to adjust this based on the actual return value of your contract + const balance = BigInt(response.result[0]).toString(); + + // Convert to a more readable format (e.g., whole tokens instead of wei) + // This example assumes 18 decimal places, adjust as needed for each token + const readableBalance = (Number(balance) / 1e18).toFixed(4); + + return readableBalance; + } catch (error) { + console.error(`Error fetching balance for token ${tokenAddress}:`, error); + return "0"; // Return '0' in case of error + } } export const getBalances = async (walletId, setBalances) => { @@ -104,15 +102,27 @@ export const getBalances = async (walletId, setBalances) => { const data = await getTokenBalances(walletId); const updatedBalances = [ - { icon: , title: 'ETH', balance: data.ETH !== undefined ? data.ETH.toString() : '0.00' }, - { icon: , title: 'USDC', balance: data.USDC !== undefined ? data.USDC.toString() : '0.00' }, - { icon: , title: 'STRK', balance: data.STRK !== undefined ? data.STRK.toString() : '0.00' }, + { + icon: , + title: "ETH", + balance: data.ETH !== undefined ? data.ETH.toString() : "0.00", + }, + { + icon: , + title: "USDC", + balance: data.USDC !== undefined ? data.USDC.toString() : "0.00", + }, + { + icon: , + title: "STRK", + balance: data.STRK !== undefined ? data.STRK.toString() : "0.00", + }, // { icon: , title: 'DAI', balance: data.DAI !== undefined ? data.DAI.toString() : '0.00' }, dont have DAI in the constants file ]; setBalances(updatedBalances); } catch (error) { - console.error('Error fetching user balances:', error); + console.error("Error fetching user balances:", error); } }; diff --git a/frontend/test/unit/contract.test.js b/frontend/test/unit/contract.test.js index 211b0a3c..bbd0879d 100644 --- a/frontend/test/unit/contract.test.js +++ b/frontend/test/unit/contract.test.js @@ -1,159 +1,172 @@ -import { connect } from 'get-starknet'; -import axios from 'axios'; -import { deployContract, checkAndDeployContract } from '../../src/utils/contract'; -import { getDeployContractData } from '../../src/utils/constants'; +import { connect } from "get-starknet"; +import axios from "axios"; +import { + deployContract, + checkAndDeployContract, +} from "../../src/utils/contract"; +import { getDeployContractData } from "../../src/utils/constants"; + +jest.mock("get-starknet"); +jest.mock("axios"); +jest.mock("../../src/utils/constants"); + +describe("Contract Deployment Tests", () => { + const mockWalletId = "0x123..."; + const mockTransactionHash = "0xabc..."; + const mockContractAddress = "0xdef..."; + const mockBackendUrl = "http://127.0.0.1:8000"; + + beforeEach(() => { + jest.clearAllMocks(); + + process.env.REACT_APP_BACKEND_URL = mockBackendUrl; + + getDeployContractData.mockReturnValue({ + contractData: "mockContractData", + }); + }); + + describe("deployContract", () => { + test("should successfully deploy contract", async () => { + jest.setTimeout(10000); + const mockStarknet = { + isConnected: true, + account: { + deployContract: jest.fn().mockResolvedValue({ + transaction_hash: mockTransactionHash, + contract_address: mockContractAddress, + }), + waitForTransaction: jest.fn().mockResolvedValue(true), + }, + }; + connect.mockResolvedValue(mockStarknet); + + const result = await deployContract(mockWalletId); + + expect(connect).toHaveBeenCalled(); + expect(mockStarknet.account.deployContract).toHaveBeenCalledWith({ + contractData: "mockContractData", + }); + expect(mockStarknet.account.waitForTransaction).toHaveBeenCalledWith( + mockTransactionHash + ); + + expect(result).toEqual({ + transactionHash: mockTransactionHash, + contractAddress: mockContractAddress, + }); + }); + + test("should throw error if wallet is not connected", async () => { + const mockStarknet = { + isConnected: false, + }; + connect.mockResolvedValue(mockStarknet); + + await expect(deployContract(mockWalletId)).rejects.toThrow( + "Wallet not connected" + ); + }); -jest.mock('get-starknet'); -jest.mock('axios'); -jest.mock('../../src/utils/constants'); + test("should handle deployment errors correctly", async () => { + const mockError = new Error("Deployment failed"); + connect.mockRejectedValue(mockError); -describe('Contract Deployment Tests', () => { - const mockWalletId = '0x123...'; - const mockTransactionHash = '0xabc...'; - const mockContractAddress = '0xdef...'; - const mockBackendUrl = 'http://127.0.0.1:8000'; + await expect(deployContract(mockWalletId)).rejects.toThrow( + "Deployment failed" + ); + }); + }); + + describe("checkAndDeployContract", () => { + test("should deploy contract if not already deployed", async () => { + axios.get.mockResolvedValue({ + data: { is_contract_deployed: false }, + }); + + const mockStarknet = { + isConnected: true, + account: { + deployContract: jest.fn().mockResolvedValue({ + transaction_hash: mockTransactionHash, + contract_address: mockContractAddress, + }), + waitForTransaction: jest.fn().mockResolvedValue(true), + }, + }; + connect.mockResolvedValue(mockStarknet); + + axios.post.mockResolvedValue({ data: "success" }); + + await checkAndDeployContract(mockWalletId); + + expect(axios.get).toHaveBeenCalledWith( + `${mockBackendUrl}/api/check-user?wallet_id=${mockWalletId}` + ); + expect(connect).toHaveBeenCalled(); + expect(mockStarknet.account.deployContract).toHaveBeenCalledWith({ + contractData: "mockContractData", + }); + expect(axios.post).toHaveBeenCalledWith( + `${mockBackendUrl}/api/update-user-contract`, + { wallet_id: mockWalletId, contract_address: mockContractAddress } + ); + }); - beforeEach(() => { - jest.clearAllMocks(); + test("should skip deployment if contract already exists", async () => { + axios.get.mockResolvedValue({ + data: { is_contract_deployed: true }, + }); - process.env.REACT_APP_BACKEND_URL = mockBackendUrl; + await checkAndDeployContract(mockWalletId); - getDeployContractData.mockReturnValue({ - contractData: 'mockContractData' - }); + expect(axios.get).toHaveBeenCalled(); + expect(connect).not.toHaveBeenCalled(); + expect(axios.post).not.toHaveBeenCalled(); }); - describe('deployContract', () => { - test('should successfully deploy contract', async () => { - jest.setTimeout(10000); - const mockStarknet = { - isConnected: true, - account: { - deployContract: jest.fn().mockResolvedValue({ - transaction_hash: mockTransactionHash, - contract_address: mockContractAddress - }), - waitForTransaction: jest.fn().mockResolvedValue(true) - } - }; - connect.mockResolvedValue(mockStarknet); - - const result = await deployContract(mockWalletId); - - expect(connect).toHaveBeenCalled(); - expect(mockStarknet.account.deployContract).toHaveBeenCalledWith({ - contractData: 'mockContractData' - }); - expect(mockStarknet.account.waitForTransaction).toHaveBeenCalledWith(mockTransactionHash); - - expect(result).toEqual({ - transactionHash: mockTransactionHash, - contractAddress: mockContractAddress - }); - }); - - test('should throw error if wallet is not connected', async () => { - const mockStarknet = { - isConnected: false - }; - connect.mockResolvedValue(mockStarknet); - - await expect(deployContract(mockWalletId)) - .rejects - .toThrow('Wallet not connected'); - }); - - test('should handle deployment errors correctly', async () => { - const mockError = new Error('Deployment failed'); - connect.mockRejectedValue(mockError); - - await expect(deployContract(mockWalletId)) - .rejects - .toThrow('Deployment failed'); - }); + test("should handle backend check errors correctly", async () => { + const mockError = new Error("Backend error"); + axios.get.mockRejectedValue(mockError); + + console.error = jest.fn(); + + await checkAndDeployContract(mockWalletId); + + expect(console.error).toHaveBeenCalledWith( + "Error checking contract status:", + mockError + ); }); - describe('checkAndDeployContract', () => { - test('should deploy contract if not already deployed', async () => { - axios.get.mockResolvedValue({ - data: { is_contract_deployed: false } - }); - - const mockStarknet = { - isConnected: true, - account: { - deployContract: jest.fn().mockResolvedValue({ - transaction_hash: mockTransactionHash, - contract_address: mockContractAddress - }), - waitForTransaction: jest.fn().mockResolvedValue(true) - } - }; - connect.mockResolvedValue(mockStarknet); - - axios.post.mockResolvedValue({ data: 'success' }); - - await checkAndDeployContract(mockWalletId); - - expect(axios.get).toHaveBeenCalledWith(`${mockBackendUrl}/api/check-user?wallet_id=${mockWalletId}`); - expect(connect).toHaveBeenCalled(); - expect(mockStarknet.account.deployContract).toHaveBeenCalledWith({ - contractData: 'mockContractData' - }); - expect(axios.post).toHaveBeenCalledWith( - `${mockBackendUrl}/api/update-user-contract`, - { wallet_id: mockWalletId, contract_address: mockContractAddress } - ); - }); - - test('should skip deployment if contract already exists', async () => { - axios.get.mockResolvedValue({ - data: { is_contract_deployed: true } - }); - - await checkAndDeployContract(mockWalletId); - - expect(axios.get).toHaveBeenCalled(); - expect(connect).not.toHaveBeenCalled(); - expect(axios.post).not.toHaveBeenCalled(); - }); - - test('should handle backend check errors correctly', async () => { - const mockError = new Error('Backend error'); - axios.get.mockRejectedValue(mockError); - - console.error = jest.fn(); - - await checkAndDeployContract(mockWalletId); - - expect(console.error).toHaveBeenCalledWith('Error checking contract status:', mockError); - }); - - test('should handle contract update error correctly after deployment', async () => { - axios.get.mockResolvedValue({ - data: { is_contract_deployed: false } - }); - - const mockStarknet = { - isConnected: true, - account: { - deployContract: jest.fn().mockResolvedValue({ - transaction_hash: mockTransactionHash, - contract_address: mockContractAddress - }), - waitForTransaction: jest.fn().mockResolvedValue(true) - } - }; - connect.mockResolvedValue(mockStarknet); - - const mockUpdateError = new Error('Update failed'); - axios.post.mockRejectedValue(mockUpdateError); - - console.error = jest.fn(); - - await checkAndDeployContract(mockWalletId); - - expect(console.error).toHaveBeenCalledWith('Error checking contract status:', mockUpdateError); - }); + test("should handle contract update error correctly after deployment", async () => { + axios.get.mockResolvedValue({ + data: { is_contract_deployed: false }, + }); + + const mockStarknet = { + isConnected: true, + account: { + deployContract: jest.fn().mockResolvedValue({ + transaction_hash: mockTransactionHash, + contract_address: mockContractAddress, + }), + waitForTransaction: jest.fn().mockResolvedValue(true), + }, + }; + connect.mockResolvedValue(mockStarknet); + + const mockUpdateError = new Error("Update failed"); + axios.post.mockRejectedValue(mockUpdateError); + + console.error = jest.fn(); + + await checkAndDeployContract(mockWalletId); + + expect(console.error).toHaveBeenCalledWith( + "Error checking contract status:", + mockUpdateError + ); }); + }); }); diff --git a/frontend/test/unit/transaction.test.js b/frontend/test/unit/transaction.test.js index 5645145d..5aa3e17d 100644 --- a/frontend/test/unit/transaction.test.js +++ b/frontend/test/unit/transaction.test.js @@ -1,215 +1,222 @@ import { connect } from "get-starknet"; -import { sendTransaction, closePosition, handleTransaction } from "../../src/utils/transaction"; -import axios from 'axios'; +import { + sendTransaction, + closePosition, + handleTransaction, +} from "../../src/utils/transaction"; +import axios from "axios"; jest.mock("get-starknet"); jest.mock("axios"); jest.mock("starknet", () => ({ - CallData: class MockCallData { - constructor() { - return { - compile: jest.fn((fnName, args) => { - return Array.isArray(args) ? args : [args]; - }) - }; - } + CallData: class MockCallData { + constructor() { + return { + compile: jest.fn((fnName, args) => { + return Array.isArray(args) ? args : [args]; + }), + }; } + }, })); -describe('Transaction Functions', () => { - const mockTransactionHash = '0xabc123'; - const mockContractAddress = '0xdef456'; - const mockWalletId = '0x789xyz'; +describe("Transaction Functions", () => { + const mockTransactionHash = "0xabc123"; + const mockContractAddress = "0xdef456"; + const mockWalletId = "0x789xyz"; + + beforeEach(() => { + jest.clearAllMocks(); + + const mockStarknet = { + isConnected: true, + account: { + execute: jest.fn().mockResolvedValue({ + transaction_hash: mockTransactionHash, + }), + }, + provider: { + getTransactionReceipt: jest.fn().mockResolvedValue({ + status: "ACCEPTED", + }), + }, + }; + + connect.mockResolvedValue(mockStarknet); + + process.env.REACT_APP_BACKEND_URL = "http://0.0.0.0:8000"; + }); + + 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, + }); + }); - beforeEach(() => { - jest.clearAllMocks(); - - const mockStarknet = { - isConnected: true, - account: { - execute: jest.fn().mockResolvedValue({ - transaction_hash: mockTransactionHash - }), - }, - provider: { - getTransactionReceipt: jest.fn().mockResolvedValue({ - status: 'ACCEPTED' - }), - } - }; - - connect.mockResolvedValue(mockStarknet); - - process.env.REACT_APP_BACKEND_URL = 'http://0.0.0.0:8000'; + it("should throw error if wallet is not connected", async () => { + connect.mockResolvedValueOnce({ isConnected: false }); + + await expect( + sendTransaction(validLoopLiquidityData, mockContractAddress) + ).rejects.toThrow("Wallet not connected"); }); - afterEach(() => { - delete process.env.REACT_APP_BACKEND_URL; + 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"); }); - 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(); // Mock console.error - - await expect(sendTransaction(validLoopLiquidityData, mockContractAddress)) - .rejects - .toThrow('Transaction failed'); - - expect(console.error).toHaveBeenCalledWith( - 'Error sending transaction:', - expect.any(Error) - ); - }); + 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(); // Mock console.error + + 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", () => { + const mockSetError = jest.fn(); + const mockSetTokenAmount = jest.fn(); + const mockSetLoading = jest.fn(); + const mockFormData = { position_id: 1 }; + + beforeEach(() => { + mockSetError.mockClear(); + mockSetTokenAmount.mockClear(); + mockSetLoading.mockClear(); }); - 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'); - }); + it("should handle successful transaction flow", async () => { + const mockTransactionData = { + position_id: 1, + contract_address: mockContractAddress, + pool_key: "0x123", + deposit_data: { + token: "0x456", + amount: "1000", + }, + }; + + axios.post.mockResolvedValueOnce({ data: mockTransactionData }); + axios.get.mockResolvedValueOnce({ + data: { status: "open" }, + }); + + await handleTransaction( + mockWalletId, + mockFormData, + mockSetError, + mockSetTokenAmount, + mockSetLoading + ); + + expect(mockSetLoading).toHaveBeenCalledWith(true); + expect(axios.post).toHaveBeenCalledWith( + "http://0.0.0.0:8000/api/create-position", + mockFormData + ); + expect(axios.get).toHaveBeenCalledWith( + "http://0.0.0.0:8000/api/open-position", + { params: { position_id: mockTransactionData.position_id } } + ); + expect(mockSetTokenAmount).toHaveBeenCalledWith(""); + expect(mockSetLoading).toHaveBeenCalledWith(false); + expect(mockSetError).toHaveBeenCalledWith(""); }); - describe('handleTransaction', () => { - const mockSetError = jest.fn(); - const mockSetTokenAmount = jest.fn(); - const mockSetLoading = jest.fn(); - const mockFormData = { position_id: 1 }; - - beforeEach(() => { - mockSetError.mockClear(); - mockSetTokenAmount.mockClear(); - mockSetLoading.mockClear(); - }); - - it('should handle successful transaction flow', async () => { - const mockTransactionData = { - position_id: 1, - contract_address: mockContractAddress, - pool_key: '0x123', - deposit_data: { - token: '0x456', - amount: '1000' - } - }; - - axios.post.mockResolvedValueOnce({ data: mockTransactionData }); - axios.get.mockResolvedValueOnce({ - data: { status: 'open' } - }); - - await handleTransaction( - mockWalletId, - mockFormData, - mockSetError, - mockSetTokenAmount, - mockSetLoading - ); - - expect(mockSetLoading).toHaveBeenCalledWith(true); - expect(axios.post).toHaveBeenCalledWith( - 'http://0.0.0.0:8000/api/create-position', - mockFormData - ); - expect(axios.get).toHaveBeenCalledWith( - 'http://0.0.0.0:8000/api/open-position', - { params: { position_id: mockTransactionData.position_id } } - ); - expect(mockSetTokenAmount).toHaveBeenCalledWith(''); - expect(mockSetLoading).toHaveBeenCalledWith(false); - expect(mockSetError).toHaveBeenCalledWith(''); - }); - - it('should handle create position error', async () => { - const mockError = new Error('Create position failed'); - axios.post.mockRejectedValueOnce(mockError); - - console.error = jest.fn(); - - await handleTransaction( - mockWalletId, - mockFormData, - mockSetError, - mockSetTokenAmount, - mockSetLoading - ); - - expect(mockSetError).toHaveBeenCalledWith( - 'Failed to create position. Please try again.' - ); - expect(console.error).toHaveBeenCalledWith( - 'Failed to create position:', - mockError - ); - expect(mockSetLoading).toHaveBeenCalledWith(false); - }); + it("should handle create position error", async () => { + const mockError = new Error("Create position failed"); + axios.post.mockRejectedValueOnce(mockError); + + console.error = jest.fn(); + + await handleTransaction( + mockWalletId, + mockFormData, + mockSetError, + mockSetTokenAmount, + mockSetLoading + ); + + expect(mockSetError).toHaveBeenCalledWith( + "Failed to create position. Please try again." + ); + expect(console.error).toHaveBeenCalledWith( + "Failed to create position:", + mockError + ); + expect(mockSetLoading).toHaveBeenCalledWith(false); }); -}); \ No newline at end of file + }); +}); diff --git a/frontend/test/unit/wallet.test.js b/frontend/test/unit/wallet.test.js index f7a5c16d..2ddc2571 100644 --- a/frontend/test/unit/wallet.test.js +++ b/frontend/test/unit/wallet.test.js @@ -1,36 +1,45 @@ -import { connect } from 'get-starknet'; -import { connectWallet, getTokenBalances, getBalances, logout } from '../../src/utils/wallet'; -import { ETH_ADDRESS, STRK_ADDRESS, USDC_ADDRESS } from "../../src/utils/constants"; +import { connect } from "get-starknet"; +import { + connectWallet, + getTokenBalances, + getBalances, + logout, +} from "../../src/utils/wallet"; +import { + ETH_ADDRESS, + STRK_ADDRESS, + USDC_ADDRESS, +} from "../../src/utils/constants"; // Mock SVG imports -jest.mock('../assets/icons/ethereum.svg', () => ({ - ReactComponent: () => 'ETH-icon', +jest.mock("../assets/icons/ethereum.svg", () => ({ + ReactComponent: () => "ETH-icon", })); -jest.mock('../assets/icons/borrow_usdc.svg', () => ({ - ReactComponent: () => 'USDC-icon', +jest.mock("../assets/icons/borrow_usdc.svg", () => ({ + ReactComponent: () => "USDC-icon", })); -jest.mock('../assets/icons/strk.svg', () => ({ - ReactComponent: () => 'STRK-icon', +jest.mock("../assets/icons/strk.svg", () => ({ + ReactComponent: () => "STRK-icon", })); -jest.mock('../assets/icons/dai.svg', () => ({ - ReactComponent: () => 'DAI-icon', +jest.mock("../assets/icons/dai.svg", () => ({ + ReactComponent: () => "DAI-icon", })); -jest.mock('get-starknet', () => ({ +jest.mock("get-starknet", () => ({ connect: jest.fn(), })); -describe('Wallet Functions', () => { +describe("Wallet Functions", () => { beforeEach(() => { jest.clearAllMocks(); }); - describe('connectWallet', () => { - it('should successfully connect wallet and return address', async () => { + describe("connectWallet", () => { + it("should successfully connect wallet and return address", async () => { const mockStarknet = { enable: jest.fn(), isConnected: true, - selectedAddress: '0x123', + selectedAddress: "0x123", }; connect.mockResolvedValue(mockStarknet); @@ -38,20 +47,22 @@ describe('Wallet Functions', () => { const address = await connectWallet(); expect(connect).toHaveBeenCalledWith({ - modalMode: 'alwaysAsk', - modalTheme: 'light', + modalMode: "alwaysAsk", + modalTheme: "light", }); expect(mockStarknet.enable).toHaveBeenCalled(); - expect(address).toBe('0x123'); + expect(address).toBe("0x123"); }); - it('should throw error when Starknet object is not found', async () => { + it("should throw error when Starknet object is not found", async () => { connect.mockResolvedValue(null); - await expect(connectWallet()).rejects.toThrow('Failed to connect to wallet'); + await expect(connectWallet()).rejects.toThrow( + "Failed to connect to wallet" + ); }); - it('should throw error when wallet connection fails', async () => { + it("should throw error when wallet connection fails", async () => { const mockStarknet = { enable: jest.fn(), isConnected: false, @@ -59,21 +70,20 @@ describe('Wallet Functions', () => { connect.mockResolvedValue(mockStarknet); - await expect(connectWallet()).rejects.toThrow('Wallet connection failed'); + await expect(connectWallet()).rejects.toThrow("Wallet connection failed"); }); }); - - describe('getTokenBalances', () => { - it('should fetch all token balances successfully', async () => { + describe("getTokenBalances", () => { + it("should fetch all token balances successfully", async () => { const mockStarknet = { isConnected: true, provider: { callContract: jest.fn().mockImplementation(({ contractAddress }) => { const mockBalances = { - [ETH_ADDRESS]: { result: ['1000000000000000000'] }, - [USDC_ADDRESS]: { result: ['1000000000000000000'] }, - [STRK_ADDRESS]: { result: ['2000000000000000000'] }, + [ETH_ADDRESS]: { result: ["1000000000000000000"] }, + [USDC_ADDRESS]: { result: ["1000000000000000000"] }, + [STRK_ADDRESS]: { result: ["2000000000000000000"] }, }; return mockBalances[contractAddress]; }), @@ -82,51 +92,57 @@ describe('Wallet Functions', () => { connect.mockResolvedValue(mockStarknet); - const balances = await getTokenBalances('0x123'); + const balances = await getTokenBalances("0x123"); expect(balances).toEqual({ - ETH: '1.0000', - USDC: '1.0000', - STRK: '2.0000' + ETH: "1.0000", + USDC: "1.0000", + STRK: "2.0000", }); }); - it('should throw error when wallet is not connected', async () => { + it("should throw error when wallet is not connected", async () => { const mockStarknet = { isConnected: false }; connect.mockResolvedValue(mockStarknet); - await expect(getTokenBalances('0x123')).rejects.toThrow('Wallet not connected'); + await expect(getTokenBalances("0x123")).rejects.toThrow( + "Wallet not connected" + ); }); }); - describe('getBalances', () => { - it('should update balances state with token balances', async () => { + describe("getBalances", () => { + it("should update balances state with token balances", async () => { const mockSetBalances = jest.fn(); - const mockWalletId = '0x123'; + const mockWalletId = "0x123"; const mockTokenBalances = [ - { name: 'ETH', balance: '1.0000', icon: 'ETH-icon' }, - { name: 'USDC', balance: '2.0000', icon: 'USDC-icon' }, - { name: 'STRK', balance: '3.0000', icon: 'STRK-icon'}, + { name: "ETH", balance: "1.0000", icon: "ETH-icon" }, + { name: "USDC", balance: "2.0000", icon: "USDC-icon" }, + { name: "STRK", balance: "3.0000", icon: "STRK-icon" }, ]; // Mock the getTokenBalances function - jest.spyOn(require('../../src/utils/wallet'), 'getTokenBalances') + jest + .spyOn(require("../../src/utils/wallet"), "getTokenBalances") .mockResolvedValue(mockTokenBalances); await getBalances(mockWalletId, mockSetBalances); await mockSetBalances(mockTokenBalances); expect(mockSetBalances).toHaveBeenCalledWith([ - { name: 'ETH', balance: '1.0000', icon: 'ETH-icon' }, - { name: 'USDC', balance: '2.0000', icon: 'USDC-icon' }, - { name: 'STRK', balance: '3.0000', icon: 'STRK-icon'}, + { name: "ETH", balance: "1.0000", icon: "ETH-icon" }, + { name: "USDC", balance: "2.0000", icon: "USDC-icon" }, + { name: "STRK", balance: "3.0000", icon: "STRK-icon" }, ]); }); - it('should not fetch balances if wallet ID is not provided', async () => { + it("should not fetch balances if wallet ID is not provided", async () => { const mockSetBalances = jest.fn(); - const mockGetTokenBalances = jest.spyOn(require('../../src/utils/wallet'), 'getTokenBalances'); + const mockGetTokenBalances = jest.spyOn( + require("../../src/utils/wallet"), + "getTokenBalances" + ); await getBalances(null, mockSetBalances); @@ -135,10 +151,10 @@ describe('Wallet Functions', () => { }); }); - describe('logout', () => { - it('should clear wallet ID from local storage', () => { + describe("logout", () => { + it("should clear wallet ID from local storage", () => { const mockRemoveItem = jest.fn(); - Object.defineProperty(window, 'localStorage', { + Object.defineProperty(window, "localStorage", { value: { removeItem: mockRemoveItem, }, @@ -147,7 +163,7 @@ describe('Wallet Functions', () => { logout(); - expect(mockRemoveItem).toHaveBeenCalledWith('wallet_id'); + expect(mockRemoveItem).toHaveBeenCalledWith("wallet_id"); }); }); -}); \ No newline at end of file +}); From 458f97ea5e07223b0f5e281294daf77b54ad92ca Mon Sep 17 00:00:00 2001 From: Isaac Onyemaechi Date: Sat, 26 Oct 2024 14:27:58 +0100 Subject: [PATCH 4/6] fix: renamed unit folder to utils --- frontend/test/{unit => utils}/contract.test.js | 0 frontend/test/{unit => utils}/transaction.test.js | 0 frontend/test/{unit => utils}/wallet.test.js | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename frontend/test/{unit => utils}/contract.test.js (100%) rename frontend/test/{unit => utils}/transaction.test.js (100%) rename frontend/test/{unit => utils}/wallet.test.js (100%) diff --git a/frontend/test/unit/contract.test.js b/frontend/test/utils/contract.test.js similarity index 100% rename from frontend/test/unit/contract.test.js rename to frontend/test/utils/contract.test.js diff --git a/frontend/test/unit/transaction.test.js b/frontend/test/utils/transaction.test.js similarity index 100% rename from frontend/test/unit/transaction.test.js rename to frontend/test/utils/transaction.test.js diff --git a/frontend/test/unit/wallet.test.js b/frontend/test/utils/wallet.test.js similarity index 100% rename from frontend/test/unit/wallet.test.js rename to frontend/test/utils/wallet.test.js From 88fdfbbf7e9e17eb428a4214ec319f6aeab46853 Mon Sep 17 00:00:00 2001 From: Isaac Onyemaechi Date: Sat, 26 Oct 2024 15:03:13 +0100 Subject: [PATCH 5/6] fix: all comments fixed --- frontend/test/constants.js | 1 + frontend/test/utils/contract.test.js | 16 ++++++++-------- frontend/test/utils/transaction.test.js | 2 +- frontend/test/utils/wallet.test.js | 8 +------- 4 files changed, 11 insertions(+), 16 deletions(-) create mode 100644 frontend/test/constants.js diff --git a/frontend/test/constants.js b/frontend/test/constants.js new file mode 100644 index 00000000..5a13f522 --- /dev/null +++ b/frontend/test/constants.js @@ -0,0 +1 @@ +export const mockBackendUrl = "http://127.0.0.1:8000"; \ No newline at end of file diff --git a/frontend/test/utils/contract.test.js b/frontend/test/utils/contract.test.js index bbd0879d..106de77b 100644 --- a/frontend/test/utils/contract.test.js +++ b/frontend/test/utils/contract.test.js @@ -5,6 +5,7 @@ import { checkAndDeployContract, } from "../../src/utils/contract"; import { getDeployContractData } from "../../src/utils/constants"; +import { mockBackendUrl } from "../constants"; jest.mock("get-starknet"); jest.mock("axios"); @@ -14,7 +15,6 @@ describe("Contract Deployment Tests", () => { const mockWalletId = "0x123..."; const mockTransactionHash = "0xabc..."; const mockContractAddress = "0xdef..."; - const mockBackendUrl = "http://127.0.0.1:8000"; beforeEach(() => { jest.clearAllMocks(); @@ -27,7 +27,7 @@ describe("Contract Deployment Tests", () => { }); describe("deployContract", () => { - test("should successfully deploy contract", async () => { + it("should successfully deploy contract", async () => { jest.setTimeout(10000); const mockStarknet = { isConnected: true, @@ -57,7 +57,7 @@ describe("Contract Deployment Tests", () => { }); }); - test("should throw error if wallet is not connected", async () => { + it("should throw error if wallet is not connected", async () => { const mockStarknet = { isConnected: false, }; @@ -68,7 +68,7 @@ describe("Contract Deployment Tests", () => { ); }); - test("should handle deployment errors correctly", async () => { + it("should handle deployment errors correctly", async () => { const mockError = new Error("Deployment failed"); connect.mockRejectedValue(mockError); @@ -79,7 +79,7 @@ describe("Contract Deployment Tests", () => { }); describe("checkAndDeployContract", () => { - test("should deploy contract if not already deployed", async () => { + it("should deploy contract if not already deployed", async () => { axios.get.mockResolvedValue({ data: { is_contract_deployed: false }, }); @@ -113,7 +113,7 @@ describe("Contract Deployment Tests", () => { ); }); - test("should skip deployment if contract already exists", async () => { + it("should skip deployment if contract already exists", async () => { axios.get.mockResolvedValue({ data: { is_contract_deployed: true }, }); @@ -125,7 +125,7 @@ describe("Contract Deployment Tests", () => { expect(axios.post).not.toHaveBeenCalled(); }); - test("should handle backend check errors correctly", async () => { + it("should handle backend check errors correctly", async () => { const mockError = new Error("Backend error"); axios.get.mockRejectedValue(mockError); @@ -139,7 +139,7 @@ describe("Contract Deployment Tests", () => { ); }); - test("should handle contract update error correctly after deployment", async () => { + it("should handle contract update error correctly after deployment", async () => { axios.get.mockResolvedValue({ data: { is_contract_deployed: false }, }); diff --git a/frontend/test/utils/transaction.test.js b/frontend/test/utils/transaction.test.js index 5aa3e17d..0fa3e60d 100644 --- a/frontend/test/utils/transaction.test.js +++ b/frontend/test/utils/transaction.test.js @@ -98,7 +98,7 @@ describe("Transaction Functions", () => { }, }); - console.error = jest.fn(); // Mock console.error + console.error = jest.fn(); await expect( sendTransaction(validLoopLiquidityData, mockContractAddress) diff --git a/frontend/test/utils/wallet.test.js b/frontend/test/utils/wallet.test.js index 2ddc2571..36dbc989 100644 --- a/frontend/test/utils/wallet.test.js +++ b/frontend/test/utils/wallet.test.js @@ -11,7 +11,6 @@ import { USDC_ADDRESS, } from "../../src/utils/constants"; -// Mock SVG imports jest.mock("../assets/icons/ethereum.svg", () => ({ ReactComponent: () => "ETH-icon", })); @@ -122,7 +121,6 @@ describe("Wallet Functions", () => { { name: "STRK", balance: "3.0000", icon: "STRK-icon" }, ]; - // Mock the getTokenBalances function jest .spyOn(require("../../src/utils/wallet"), "getTokenBalances") .mockResolvedValue(mockTokenBalances); @@ -130,11 +128,7 @@ describe("Wallet Functions", () => { await getBalances(mockWalletId, mockSetBalances); await mockSetBalances(mockTokenBalances); - expect(mockSetBalances).toHaveBeenCalledWith([ - { name: "ETH", balance: "1.0000", icon: "ETH-icon" }, - { name: "USDC", balance: "2.0000", icon: "USDC-icon" }, - { name: "STRK", balance: "3.0000", icon: "STRK-icon" }, - ]); + expect(mockSetBalances).toHaveBeenCalledWith(mockTokenBalances); }); it("should not fetch balances if wallet ID is not provided", async () => { From be4898db09cf22f1eb0f4206ccab899da32a48dd Mon Sep 17 00:00:00 2001 From: Isaac Onyemaechi Date: Sat, 26 Oct 2024 15:04:15 +0100 Subject: [PATCH 6/6] fix: tiny fix --- frontend/test/utils/transaction.test.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/frontend/test/utils/transaction.test.js b/frontend/test/utils/transaction.test.js index 0fa3e60d..9cf1839e 100644 --- a/frontend/test/utils/transaction.test.js +++ b/frontend/test/utils/transaction.test.js @@ -5,6 +5,7 @@ import { handleTransaction, } from "../../src/utils/transaction"; import axios from "axios"; +import { mockBackendUrl } from "../constants"; jest.mock("get-starknet"); jest.mock("axios"); @@ -45,7 +46,7 @@ describe("Transaction Functions", () => { connect.mockResolvedValue(mockStarknet); - process.env.REACT_APP_BACKEND_URL = "http://0.0.0.0:8000"; + process.env.REACT_APP_BACKEND_URL = mockBackendUrl; }); afterEach(() => {