Skip to content

Commit

Permalink
fix(extension): fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
vetalcore committed Feb 27, 2024
1 parent 5a2d1f7 commit 3769e20
Show file tree
Hide file tree
Showing 20 changed files with 240 additions and 211 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,14 @@ export const ConfirmDRepRetirementContainer = ({ onError }: Props): React.ReactE
getCertificateData();
}, [request]);

const depositPaidWithCardanoSymbol = depositPaidWithSymbol(certificate.deposit, cardanoCoin);
const isNotOwnDRepKey = certificate.dRepCredential.hash !== ownPubDRepKeyHash;
const isNotOwnDRepKey = certificate?.dRepCredential.hash !== ownPubDRepKeyHash;

useEffect(() => {
if (ownPubDRepKeyHash && isNotOwnDRepKey) {
if (ownPubDRepKeyHash && certificate && isNotOwnDRepKey) {
disallowSignTx(request, true);
onError();
}
}, [ownPubDRepKeyHash, isNotOwnDRepKey, onError, request]);
}, [ownPubDRepKeyHash, isNotOwnDRepKey, onError, request, certificate]);

const onCloseClick = useCallback(() => {
window.close();
Expand All @@ -58,6 +57,8 @@ export const ConfirmDRepRetirementContainer = ({ onError }: Props): React.ReactE
return <Skeleton loading />;
}

const depositPaidWithCardanoSymbol = depositPaidWithSymbol(certificate.deposit, cardanoCoin);

if (isNotOwnDRepKey) {
return (
<DappError
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export const DappTransactionContainer = withAddressBookContext(({ errorMessage }

const tx = request?.transaction.toCore();
if (!tx) {
return <Skeleton />;
return <Skeleton loading />;
}
const createAssetList = useCreateAssetList({
outputs: tx.body.outputs,
Expand All @@ -59,7 +59,7 @@ export const DappTransactionContainer = withAddressBookContext(({ errorMessage }

// TODO: merge with the upper skeleton check
if (!txSummary) {
return <Skeleton />;
return <Skeleton loading />;
}

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,10 @@ import { BehaviorSubject } from 'rxjs';
import { act } from 'react-dom/test-utils';
import { buildMockTx } from '@src/utils/mocks/tx';
import { Wallet } from '@lace/cardano';
import BigNumber from 'bignumber.js';
import { getWrapper } from '../testing.utils';
import { drepIDasBech32FromHash } from '../utils';
import { depositPaidWithSymbol, drepIDasBech32FromHash } from '../utils';
import { TransactionWitnessRequest } from '@cardano-sdk/web-extension';

const LOVELACE_VALUE = 1_000_000;
const DEFAULT_DECIMALS = 2;

const { Cardano, Crypto } = Wallet;

const assetInfo$ = new BehaviorSubject(new Map());
Expand Down Expand Up @@ -133,9 +129,7 @@ describe('Testing ConfirmDRepRegistrationContainer component', () => {
{
dappInfo,
metadata: {
depositPaid: `${new BigNumber(certificate.deposit.toString())
.dividedBy(LOVELACE_VALUE)
.toFixed(DEFAULT_DECIMALS)} ${cardanoCoinMock.symbol}`,
depositPaid: depositPaidWithSymbol(certificate.deposit, cardanoCoinMock as Wallet.CoinId),
drepId: drepIDasBech32FromHash(certificate.dRepCredential.hash),
hash: certificate.anchor?.dataHash,
url: certificate.anchor?.url
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const t = jest.fn().mockImplementation((res) => res);
const mockUseTranslation = jest.fn(() => ({ t }));
const mockConfirmDRepRetirement = jest.fn();
const mockDappError = jest.fn();
const mockDisallowSignTx = jest.fn();
const mockUseGetOwnPubDRepKeyHash = jest.fn();
const flowContextMock = jest.fn();

Expand All @@ -19,12 +20,9 @@ import { BehaviorSubject } from 'rxjs';
import { act } from 'react-dom/test-utils';
import { buildMockTx } from '@src/utils/mocks/tx';
import { Wallet } from '@lace/cardano';
import BigNumber from 'bignumber.js';
import { getWrapper } from '../testing.utils';
import { drepIDasBech32FromHash } from '../utils';
import { depositPaidWithSymbol, drepIDasBech32FromHash } from '../utils';
import { TransactionWitnessRequest } from '@cardano-sdk/web-extension';
const LOVELACE_VALUE = 1_000_000;
const DEFAULT_DECIMALS = 2;

const { Cardano, Crypto } = Wallet;

Expand Down Expand Up @@ -86,6 +84,15 @@ jest.mock('../hooks.ts', () => {
};
});

jest.mock('../utils.ts', () => {
const original = jest.requireActual('../utils.ts');
return {
__esModule: true,
...original,
disallowSignTx: mockDisallowSignTx
};
});

jest.mock('@src/stores', () => ({
...jest.requireActual<any>('@src/stores'),
useWalletStore: mockUseWalletStore
Expand Down Expand Up @@ -121,7 +128,8 @@ jest.mock('react-i18next', () => {
describe('Testing ConfirmDRepRetirementContainer component', () => {
beforeEach(() => {
mockUseWalletStore.mockReset();
mockUseGetOwnPubDRepKeyHash.mockImplementationOnce(() => ({
mockUseGetOwnPubDRepKeyHash.mockReset();
mockUseGetOwnPubDRepKeyHash.mockImplementation(() => ({
loading: false,
ownPubDRepKeyHash: hash
}));
Expand All @@ -145,8 +153,6 @@ describe('Testing ConfirmDRepRetirementContainer component', () => {
});

afterEach(() => {
jest.resetModules();
jest.resetAllMocks();
cleanup();
});

Expand All @@ -167,9 +173,7 @@ describe('Testing ConfirmDRepRetirementContainer component', () => {
{
dappInfo,
metadata: {
depositReturned: `${new BigNumber(certificate.deposit.toString())
.dividedBy(LOVELACE_VALUE)
.toFixed(DEFAULT_DECIMALS)} ${cardanoCoinMock.symbol}`,
depositReturned: depositPaidWithSymbol(certificate.deposit, cardanoCoinMock as Wallet.CoinId),
drepId: drepIDasBech32FromHash(certificate.dRepCredential.hash)
},
translations: {
Expand All @@ -186,10 +190,9 @@ describe('Testing ConfirmDRepRetirementContainer component', () => {

test('should render ConfirmDRepRetirementContainer component with proper error for own retirement', async () => {
let queryByTestId: any;
const additionalProps = { onError: onErrorMock };

await act(async () => {
({ queryByTestId } = render(<ConfirmDRepRetirementContainer {...additionalProps} />, {
({ queryByTestId } = render(<ConfirmDRepRetirementContainer {...props} />, {
wrapper: getWrapper()
}));
});
Expand All @@ -204,14 +207,16 @@ describe('Testing ConfirmDRepRetirementContainer component', () => {
ownPubDRepKeyHash: Crypto.Hash28ByteBase16(Buffer.from('WRONG_dRepCredentialHashdRep').toString('hex'))
}));
let queryByTestId: any;
const additionalProps = { onError: onErrorMock };

await act(async () => {
({ queryByTestId } = render(<ConfirmDRepRetirementContainer {...additionalProps} />, {
({ queryByTestId } = render(<ConfirmDRepRetirementContainer {...props} />, {
wrapper: getWrapper()
}));
});

expect(queryByTestId('DappError')).toBeInTheDocument();
expect(onErrorMock).toBeCalledTimes(1);
expect(mockDisallowSignTx).toBeCalledTimes(1);
expect(mockDisallowSignTx).toBeCalledWith(request, true);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { buildMockTx } from '@src/utils/mocks/tx';
import { Wallet } from '@lace/cardano';
import { getWrapper } from '../testing.utils';
import { TransactionWitnessRequest } from '@cardano-sdk/web-extension';
import { depositPaidWithSymbol } from '../utils';

const REWARD_ACCOUNT = Wallet.Cardano.RewardAccount('stake_test1uqrw9tjymlm8wrwq7jk68n6v7fs9qz8z0tkdkve26dylmfc2ux2hj');
const STAKE_KEY_HASH = Wallet.Cardano.RewardAccount.toHash(REWARD_ACCOUNT);
Expand Down Expand Up @@ -148,7 +149,7 @@ describe('Testing ConfirmStakeRegistrationDelegationContainer component', () =>
metadata: {
poolId: certificate.poolId,
stakeKeyHash: 'stake_test1uqrw9tjymlm8wrwq7jk68n6v7fs9qz8z0tkdkve26dylmfc2ux2hj',
depositPaid: `${certificate.deposit.toString()} ${cardanoCoinMock.symbol}`
depositPaid: depositPaidWithSymbol(certificate.deposit, cardanoCoinMock as Wallet.CoinId)
},
translations: {
metadata: t('core.StakeRegistrationDelegation.metadata'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { act } from 'react-dom/test-utils';
import { buildMockTx } from '@src/utils/mocks/tx';
import { Wallet } from '@lace/cardano';
import { getWrapper } from '../testing.utils';
import { drepIDasBech32FromHash } from '../utils';
import { depositPaidWithSymbol, drepIDasBech32FromHash } from '../utils';
import { TransactionWitnessRequest } from '@cardano-sdk/web-extension';

const REWARD_ACCOUNT = Wallet.Cardano.RewardAccount('stake_test1uqrw9tjymlm8wrwq7jk68n6v7fs9qz8z0tkdkve26dylmfc2ux2hj');
Expand Down Expand Up @@ -173,7 +173,7 @@ describe('Testing ConfirmStakeVoteRegistrationDelegationContainer component', ()
metadata: {
poolId: certificate.poolId,
stakeKeyHash: 'stake_test1uqrw9tjymlm8wrwq7jk68n6v7fs9qz8z0tkdkve26dylmfc2ux2hj',
depositPaid: `${certificate.deposit.toString()} ${cardanoCoinMock.symbol}`,
depositPaid: depositPaidWithSymbol(certificate.deposit, cardanoCoinMock as Wallet.CoinId),
alwaysAbstain: isDRepAlwaysAbstainMocked,
alwaysNoConfidence: isDRepAlwaysNoConfidenceMocked,
drepId: drepIDasBech32FromHash((certificate.dRep as Wallet.Cardano.Credential).hash)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
/* eslint-disable import/imports-first */
const mockGetKeyAgentType = jest.fn();
const mockUseWalletStore = jest.fn();
const error = 'error in getSignTxData';
const mockConsumeRemoteApi = jest.fn();
const mockExposeApi = jest.fn(() => ({ shutdown: jest.fn() }));
const mockConfirmTransactionContent = jest.fn(() => <span data-testid="ConfirmTransactionContent" />);
const mockGetTxType = jest.fn();
const mockUseDisallowSignTx = jest.fn();
Expand Down Expand Up @@ -52,7 +51,7 @@ jest.mock('@cardano-sdk/web-extension', () => {
return {
__esModule: true,
...original,
consumeRemoteApi: mockConsumeRemoteApi
exposeApi: mockExposeApi
};
});

Expand Down Expand Up @@ -130,7 +129,8 @@ describe('Testing ConfirmTransaction component', () => {
signTxRequest: {
request: {
transaction: {
toCore: jest.fn().mockReturnValue({ id: 'test-tx-id' })
toCore: jest.fn().mockReturnValue({ id: 'test-tx-id' }),
getId: jest.fn().mockReturnValue({ id: 'test-tx-id' })
}
}
}
Expand All @@ -140,8 +140,6 @@ describe('Testing ConfirmTransaction component', () => {
});

afterEach(() => {
jest.resetModules();
jest.resetAllMocks();
cleanup();
});

Expand All @@ -163,10 +161,6 @@ describe('Testing ConfirmTransaction component', () => {
mockGetTxType.mockReturnValue(txType);

const signTxData = { tx: { id: 'test-tx-id' } };
mockConsumeRemoteApi.mockReset();
mockConsumeRemoteApi.mockReturnValue({
getSignTxData: async () => await Promise.resolve(signTxData)
});
const disallowSignTx = jest.fn();
mockUseDisallowSignTx.mockReset();
mockUseDisallowSignTx.mockReturnValue(disallowSignTx);
Expand All @@ -177,7 +171,8 @@ describe('Testing ConfirmTransaction component', () => {
signTxRequest: {
request: {
transaction: {
toCore: jest.fn().mockReturnValue({ id: 'test-tx-id' })
getId: jest.fn().mockReturnValue({ id: 'test-tx-id' }),
toCore: jest.fn().mockReturnValue(signTxData.tx)
}
}
}
Expand All @@ -194,8 +189,6 @@ describe('Testing ConfirmTransaction component', () => {
expect(mockConfirmTransactionContent).toHaveBeenLastCalledWith(
{
txType,
signTxData,
errorMessage: undefined,
onError: expect.any(Function)
},
{}
Expand Down Expand Up @@ -227,16 +220,13 @@ describe('Testing ConfirmTransaction component', () => {
mockUseWalletStore.mockImplementation(() => ({
getKeyAgentType: mockGetKeyAgentType,
inMemoryWallet,
isHardwareWallet: true,
walletType: 'Ledger',
walletUI: {},
walletInfo: {},
blockchainProvider: { assetProvider }
}));

const signTxData = { tx: { id: 'test-tx-id' } };
mockConsumeRemoteApi.mockReset();
mockConsumeRemoteApi.mockReturnValue({
getSignTxData: async () => await Promise.resolve(signTxData)
});
const signWithHardwareWalletMock = jest.fn();
mockUseSignWithHardwareWallet.mockReset();
mockUseSignWithHardwareWallet.mockReturnValue({ signWithHardwareWallet: signWithHardwareWalletMock });
Expand All @@ -255,34 +245,4 @@ describe('Testing ConfirmTransaction component', () => {

expect(signWithHardwareWalletMock).toHaveBeenCalled();
});

test('should disable confirm button and show proper error if getSignTxData throws', async () => {
let queryByTestId: any;
const txType = 'txType';
mockUseWalletStore.mockImplementation(() => ({
getKeyAgentType: mockGetKeyAgentType,
inMemoryWallet,
walletUI: {},
walletInfo: {},
blockchainProvider: { assetProvider }
}));
mockConsumeRemoteApi.mockReset();
mockConsumeRemoteApi.mockReturnValue({
getSignTxData: async () => await Promise.reject(error)
});
mockGetTxType.mockReset();
mockGetTxType.mockReturnValue(txType);
await act(async () => {
({ queryByTestId } = render(<ConfirmTransaction />, {
wrapper: getWrapper()
}));
});

expect(queryByTestId('ConfirmTransactionContent')).toBeInTheDocument();
expect(mockConfirmTransactionContent).toHaveBeenLastCalledWith(
{ errorMessage: error, onError: expect.any(Function), signTxData: undefined, txType: undefined },
{}
);
expect(queryByTestId(testIds.dappTransactionConfirm).closest('button')).toHaveAttribute('disabled');
});
});
Loading

0 comments on commit 3769e20

Please sign in to comment.