From 8c16d8d5a3370723de5449138529e00256110560 Mon Sep 17 00:00:00 2001 From: andrea Date: Tue, 2 Jul 2024 16:12:03 -0700 Subject: [PATCH] Remove `@types/jest`, and use Jest's own type annotations instead --- ironfish-cli/src/testHarness.ts | 25 ++++++++ .../src/utils/chainport/utils.test.ts | 7 +- ironfish-rust-nodejs/package.json | 1 - ironfish-rust-nodejs/tests/testHarness.ts | 25 ++++++++ ironfish/package.json | 1 - ironfish/src/assets/assetsVerifier.test.ts | 3 +- ironfish/src/chainProcessor.test.ts | 9 +-- ironfish/src/event.test.ts | 2 +- ironfish/src/genesis/genesis.test.slow.ts | 13 ++-- ironfish/src/memPool/memPool.test.ts | 4 +- ironfish/src/network/blockFetcher.test.ts | 8 ++- ironfish/src/network/peerNetwork.test.ts | 8 ++- .../peers/connections/connection.test.ts | 4 +- ironfish/src/network/peers/peer.test.ts | 2 +- .../src/network/peers/peerManager.test.ts | 18 ++++-- ironfish/src/network/testUtilities/helpers.ts | 3 +- .../src/network/transactionFetcher.test.ts | 2 +- .../src/rpc/routes/faucet/getFunds.test.ts | 12 ++-- ironfish/src/rpc/routes/node/stopNode.test.ts | 2 +- ironfish/src/sdk.test.ts | 4 +- ironfish/src/storage/database.test.ts | 28 ++++---- .../src/storage/database/encoding.test.ts | 24 +++---- ironfish/src/syncer.test.ts | 6 +- ironfish/src/telemetry/telemetry.test.ts | 4 +- ironfish/src/testHarness.ts | 25 ++++++++ .../src/testUtilities/matchers/blockchain.ts | 27 ++++---- ironfish/src/testUtilities/matchers/buffer.ts | 12 ++-- .../src/testUtilities/matchers/merkletree.ts | 24 +++---- ironfish/src/testUtilities/matchers/string.ts | 12 ++-- ironfish/src/testUtilities/mocks.ts | 4 +- ironfish/src/testUtilities/utils.test.ts | 53 --------------- ironfish/src/testUtilities/utils.ts | 64 ------------------- ironfish/src/utils/retry.test.ts | 6 +- .../src/wallet/scanner/noteDecryptor.test.ts | 5 +- .../scanner/remoteChainProcessor.test.ts | 5 +- ironfish/src/wallet/wallet.test.slow.ts | 5 +- ironfish/src/wallet/wallet.test.ts | 2 +- .../workerPool/tasks/submitTelemetry.test.ts | 4 +- package.json | 1 - yarn.lock | 58 +---------------- 40 files changed, 220 insertions(+), 302 deletions(-) create mode 100644 ironfish-cli/src/testHarness.ts create mode 100644 ironfish-rust-nodejs/tests/testHarness.ts create mode 100644 ironfish/src/testHarness.ts delete mode 100644 ironfish/src/testUtilities/utils.test.ts diff --git a/ironfish-cli/src/testHarness.ts b/ironfish-cli/src/testHarness.ts new file mode 100644 index 0000000000..f89eb8062d --- /dev/null +++ b/ironfish-cli/src/testHarness.ts @@ -0,0 +1,25 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ +import type { Jest } from '@jest/environment' +import type { JestExpect } from '@jest/expect' +import type { Global } from '@jest/types' + +declare global { + const { + it, + test, + fit, + xit, + xtest, + describe, + xdescribe, + fdescribe, + beforeAll, + beforeEach, + afterEach, + afterAll, + }: Global.GlobalAdditions + const expect: JestExpect + const jest: Jest +} diff --git a/ironfish-cli/src/utils/chainport/utils.test.ts b/ironfish-cli/src/utils/chainport/utils.test.ts index 53582df2e6..74ef594fef 100644 --- a/ironfish-cli/src/utils/chainport/utils.test.ts +++ b/ironfish-cli/src/utils/chainport/utils.test.ts @@ -1,6 +1,7 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ +import type { Mock } from 'jest-mock' import { RpcWalletNote, RpcWalletTransaction, TransactionType } from '@ironfish/sdk' import { getConfig } from './config' import { ChainportMemoMetadata } from './metadata' @@ -16,7 +17,7 @@ describe('isChainportTransaction', () => { } beforeEach(() => { - ;(getConfig as jest.Mock).mockReturnValue(mockConfig) + ;(getConfig as Mock).mockReturnValue(mockConfig) }) it('should return false for non-SEND/RECEIVE transactions', () => { @@ -42,7 +43,7 @@ describe('isChainportTransaction', () => { }) it('should return true for valid incoming chainport transaction', () => { - ;(ChainportMemoMetadata.decode as jest.Mock).mockReturnValue([1, 'address']) + ;(ChainportMemoMetadata.decode as Mock).mockReturnValue([1, 'address']) const transaction = { type: TransactionType.RECEIVE, @@ -92,7 +93,7 @@ describe('isChainportTransaction', () => { }) it('should return true for valid outgoing chainport transaction', () => { - ;(ChainportMemoMetadata.decode as jest.Mock).mockReturnValue([1, 'address']) + ;(ChainportMemoMetadata.decode as Mock).mockReturnValue([1, 'address']) const transaction = { type: TransactionType.SEND, notes: [ diff --git a/ironfish-rust-nodejs/package.json b/ironfish-rust-nodejs/package.json index 3b75843e3b..8282c3ef0c 100644 --- a/ironfish-rust-nodejs/package.json +++ b/ironfish-rust-nodejs/package.json @@ -35,7 +35,6 @@ }, "devDependencies": { "@napi-rs/cli": "2.16.1", - "@types/jest": "29.5.8", "jest": "29.7.0", "rimraf": "3.0.2", "ts-jest": "29.1.1", diff --git a/ironfish-rust-nodejs/tests/testHarness.ts b/ironfish-rust-nodejs/tests/testHarness.ts new file mode 100644 index 0000000000..f89eb8062d --- /dev/null +++ b/ironfish-rust-nodejs/tests/testHarness.ts @@ -0,0 +1,25 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ +import type { Jest } from '@jest/environment' +import type { JestExpect } from '@jest/expect' +import type { Global } from '@jest/types' + +declare global { + const { + it, + test, + fit, + xit, + xtest, + describe, + xdescribe, + fdescribe, + beforeAll, + beforeEach, + afterEach, + afterAll, + }: Global.GlobalAdditions + const expect: JestExpect + const jest: Jest +} diff --git a/ironfish/package.json b/ironfish/package.json index ac067139f2..e5dae413cb 100644 --- a/ironfish/package.json +++ b/ironfish/package.json @@ -71,7 +71,6 @@ "@types/buffer-json": "2.0.0", "@types/colors": "1.2.1", "@types/imurmurhash": "0.1.1", - "@types/jest": "29.5.8", "@types/leveldown": "4.0.2", "@types/levelup": "4.3.0", "@types/lodash": "4.14.170", diff --git a/ironfish/src/assets/assetsVerifier.test.ts b/ironfish/src/assets/assetsVerifier.test.ts index e6bdcf273a..83b182d16a 100644 --- a/ironfish/src/assets/assetsVerifier.test.ts +++ b/ironfish/src/assets/assetsVerifier.test.ts @@ -1,6 +1,7 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ +import type { SpyInstance } from 'jest-mock' import nock from 'nock' import { VerifiedAssetsCacheStore } from '../fileStores/verifiedAssets' import { NodeFileProvider } from '../fileSystems' @@ -35,7 +36,7 @@ const assetData3 = { describe('AssetsVerifier', () => { jest.useFakeTimers() - const waitForRefreshToFinish = async (refreshSpy: jest.SpyInstance) => { + const waitForRefreshToFinish = async (refreshSpy: SpyInstance) => { for (const result of refreshSpy.mock.results) { await result.value } diff --git a/ironfish/src/chainProcessor.test.ts b/ironfish/src/chainProcessor.test.ts index 5b230a7b7c..e9b614bfe0 100644 --- a/ironfish/src/chainProcessor.test.ts +++ b/ironfish/src/chainProcessor.test.ts @@ -2,6 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ +import type { Mock } from 'jest-mock' import { ChainProcessor } from './chainProcessor' import { BlockHeader } from './primitives/blockheader' import { createNodeTest, useMinerBlockFixture } from './testUtilities' @@ -32,7 +33,7 @@ describe('ChainProcessor', () => { head: chain.genesis.hash, }) - const onEvent: jest.Mock = jest.fn() + const onEvent: Mock<(header: BlockHeader, event: 'add' | 'remove') => void> = jest.fn() processor.onAdd.on((block) => onEvent(block, 'add')) processor.onRemove.on((block) => onEvent(block, 'remove')) @@ -82,7 +83,7 @@ describe('ChainProcessor', () => { head: chain.genesis.hash, }) - const onEvent: jest.Mock = jest.fn() + const onEvent: Mock<(header: BlockHeader, event: 'add' | 'remove') => void> = jest.fn() processor.onAdd.on((block) => onEvent(block, 'add')) processor.onRemove.on((block) => onEvent(block, 'remove')) @@ -149,7 +150,7 @@ describe('ChainProcessor', () => { expect(chain.head.hash).toEqual(block2.header.hash) - const onEvent: jest.Mock = jest.fn() + const onEvent: Mock<(header: BlockHeader, event: 'add' | 'remove') => void> = jest.fn() const processor = new ChainProcessor({ chain, head: null }) processor.onAdd.on((block) => onEvent(block, 'add')) @@ -178,7 +179,7 @@ describe('ChainProcessor', () => { await expect(chain).toAddBlock(block) expect(chain.head.hash).toEqual(block.header.hash) - const onEvent: jest.Mock = jest.fn() + const onEvent: Mock<(header: BlockHeader, event: 'add' | 'remove') => void> = jest.fn() const processor = new ChainProcessor({ chain, head: chain.genesis.hash }) processor.onAdd.on((block) => onEvent(block, 'add')) diff --git a/ironfish/src/event.test.ts b/ironfish/src/event.test.ts index 6b11f1341b..97abdd7869 100644 --- a/ironfish/src/event.test.ts +++ b/ironfish/src/event.test.ts @@ -44,7 +44,7 @@ describe('Event', () => { it('should remove once', () => { const event = new Event<[]>() - const mock = jest.fn() + const mock = jest.fn<() => void>() event.once(mock) diff --git a/ironfish/src/genesis/genesis.test.slow.ts b/ironfish/src/genesis/genesis.test.slow.ts index 7868b63df8..0dee91aaf6 100644 --- a/ironfish/src/genesis/genesis.test.slow.ts +++ b/ironfish/src/genesis/genesis.test.slow.ts @@ -1,6 +1,7 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ +import type { SpiedFunction } from 'jest-mock' import { Asset, generateKey } from '@ironfish/rust-nodejs' import { BlockSerde, SerializedBlock } from '../primitives/block' import { Target } from '../primitives/target' @@ -13,8 +14,8 @@ import { GenesisBlockInfo, makeGenesisBlock } from './makeGenesisBlock' describe('Read genesis block', () => { const nodeTest = createNodeTest() - let targetMeetsSpy: jest.SpyInstance - let targetSpy: jest.SpyInstance + let targetMeetsSpy: SpiedFunction + let targetSpy: SpiedFunction beforeAll(() => { targetMeetsSpy = jest.spyOn(Target, 'meets').mockImplementation(() => true) @@ -41,8 +42,8 @@ describe('Read genesis block', () => { describe('Create genesis block', () => { const nodeTest = createNodeTest(false, { autoSeed: false }) - let targetMeetsSpy: jest.SpyInstance - let targetSpy: jest.SpyInstance + let targetMeetsSpy: SpiedFunction + let targetSpy: SpiedFunction beforeAll(() => { targetMeetsSpy = jest.spyOn(Target, 'meets').mockImplementation(() => true) @@ -151,8 +152,8 @@ describe('Create genesis block', () => { describe('addGenesisTransaction', () => { const nodeTest = createNodeTest(false, { autoSeed: false }) - let targetMeetsSpy: jest.SpyInstance - let targetSpy: jest.SpyInstance + let targetMeetsSpy: SpiedFunction + let targetSpy: SpiedFunction beforeAll(() => { targetMeetsSpy = jest.spyOn(Target, 'meets').mockImplementation(() => true) diff --git a/ironfish/src/memPool/memPool.test.ts b/ironfish/src/memPool/memPool.test.ts index d1ecac23b6..1634f838d2 100644 --- a/ironfish/src/memPool/memPool.test.ts +++ b/ironfish/src/memPool/memPool.test.ts @@ -277,7 +277,9 @@ describe('MemPool', () => { describe('with an expired sequence', () => { const nodeTest = createNodeTest() - afterEach(() => jest.restoreAllMocks()) + afterEach(() => { + jest.restoreAllMocks() + }) it('returns false', async () => { const { node } = nodeTest diff --git a/ironfish/src/network/blockFetcher.test.ts b/ironfish/src/network/blockFetcher.test.ts index 8231b412c5..3854951bff 100644 --- a/ironfish/src/network/blockFetcher.test.ts +++ b/ironfish/src/network/blockFetcher.test.ts @@ -71,7 +71,7 @@ describe('BlockFetcher', () => { expect(sentPeers).toHaveLength(1) expect(sentPeers[0].sendSpy).toHaveBeenCalledWith( - new GetCompactBlockRequest(hash, expect.any(Number)), + new GetCompactBlockRequest(hash, expect.any(Number) as unknown as number), ) await peerNetwork.stop() @@ -177,7 +177,11 @@ describe('BlockFetcher', () => { expect(peers[0].sendSpy.mock.calls).toHaveLength(1) const request = peers[0].sendSpy.mock.calls[0][0] expect(request).toEqual( - new GetBlockTransactionsRequest(block.header.hash, [1, 0, 1, 0], expect.any(Number)), + new GetBlockTransactionsRequest( + block.header.hash, + [1, 0, 1, 0], + expect.any(Number) as unknown as number, + ), ) expect(await chain.hasBlock(block.header.hash)).toBe(false) diff --git a/ironfish/src/network/peerNetwork.test.ts b/ironfish/src/network/peerNetwork.test.ts index 10d93bbcda..8d91865ccc 100644 --- a/ironfish/src/network/peerNetwork.test.ts +++ b/ironfish/src/network/peerNetwork.test.ts @@ -111,7 +111,7 @@ describe('PeerNetwork', () => { expect(peerNetwork.isReady).toBe(false) - const readyChanged = jest.fn() + const readyChanged = jest.fn<(ready: boolean) => void>() peerNetwork.onIsReadyChanged.on(readyChanged) peerNetwork.start() @@ -893,7 +893,8 @@ describe('PeerNetwork', () => { // Don't sync incoming transactions to wallet since its done async and will // attempt to update the wallet after the test has finished peerNetwork.onTransactionGossipReceived.clear() - const onTransactionGossipReceivedSpy = jest.fn() + const onTransactionGossipReceivedSpy = + jest.fn<(transaction: Transaction, valid: boolean) => void>() peerNetwork.onTransactionGossipReceived.on(onTransactionGossipReceivedSpy) await peerNetwork.peerManager.onMessage.emitAsync( @@ -1161,7 +1162,8 @@ describe('PeerNetwork', () => { // Don't sync incoming transactions to wallet since its done async and will // attempt to update the wallet after the test has finished peerNetwork.onTransactionGossipReceived.clear() - const onTransactionGossipReceivedSpy = jest.fn() + const onTransactionGossipReceivedSpy = + jest.fn<(transaction: Transaction, valid: boolean) => void>() peerNetwork.onTransactionGossipReceived.on(onTransactionGossipReceivedSpy) await peerNetwork.peerManager.onMessage.emitAsync( diff --git a/ironfish/src/network/peers/connections/connection.test.ts b/ironfish/src/network/peers/connections/connection.test.ts index ee0cb72c85..6ffa6d9663 100644 --- a/ironfish/src/network/peers/connections/connection.test.ts +++ b/ironfish/src/network/peers/connections/connection.test.ts @@ -71,7 +71,9 @@ describe('Connection', () => { features: defaultFeatures(), }) - const _sendSpy = jest.spyOn(connection, '_send').mockImplementationOnce(jest.fn()) + const _sendSpy = jest + .spyOn(connection, '_send') + .mockImplementationOnce(jest.fn<(data: Buffer) => boolean>()) expect(connection.send(message)).toBe(false) expect(_sendSpy).not.toHaveBeenCalled() diff --git a/ironfish/src/network/peers/peer.test.ts b/ironfish/src/network/peers/peer.test.ts index ebcc9caa4a..67b4b38be8 100644 --- a/ironfish/src/network/peers/peer.test.ts +++ b/ironfish/src/network/peers/peer.test.ts @@ -358,7 +358,7 @@ describe('punish', () => { connections: { webSocket: connection }, }) - const onBannedHandler = jest.fn() + const onBannedHandler = jest.fn<(reason: string) => void>() peer.onBanned.on(onBannedHandler) peer.punish(BAN_SCORE.MAX, 'TESTING') diff --git a/ironfish/src/network/peers/peerManager.test.ts b/ironfish/src/network/peers/peerManager.test.ts index 69ad2a5203..7e8ab92f87 100644 --- a/ironfish/src/network/peers/peerManager.test.ts +++ b/ironfish/src/network/peers/peerManager.test.ts @@ -9,6 +9,7 @@ import { Assert } from '../../assert' import { canInitiateWebRTC, privateIdentityToIdentity } from '../identity' import { DisconnectingMessage, DisconnectingReason } from '../messages/disconnecting' import { IdentifyMessage } from '../messages/identify' +import { NetworkMessage } from '../messages/networkMessage' import { PeerListMessage } from '../messages/peerList' import { PeerListRequestMessage } from '../messages/peerListRequest' import { SignalMessage } from '../messages/signal' @@ -30,12 +31,13 @@ import { NetworkMessageType } from '../types' import { formatWebSocketAddress } from '../utils' import { VERSION_PROTOCOL, VERSION_PROTOCOL_MIN } from '../version' import { + Connection, ConnectionDirection, ConnectionType, WebRtcConnection, WebSocketConnection, } from './connections' -import { BAN_SCORE } from './peer' +import { BAN_SCORE, Peer } from './peer' import { defaultFeatures } from './peerFeatures' import { PeerManager } from './peerManager' @@ -495,7 +497,7 @@ describe('PeerManager', () => { // Create the peer to broker the connection through const { peer: brokeringPeer } = getConnectedPeer(peers) - const brokerPeerSendMock = jest.fn() + const brokerPeerSendMock = jest.fn<(message: NetworkMessage) => Connection | null>() brokeringPeer.send = brokerPeerSendMock // Create the peer to connect to WebRTC through @@ -733,7 +735,7 @@ describe('PeerManager', () => { it('Emits onConnectedPeersChanged when a peer enters CONNECTED or DISCONNECTED', () => { const pm = new PeerManager(mockLocalPeer(), mockPeerStore()) - const onConnectedPeersChangedMock = jest.fn() + const onConnectedPeersChangedMock = jest.fn<() => void>() pm.onConnectedPeersChanged.on(onConnectedPeersChangedMock) const { peer: connecting } = getConnectingPeer(pm) @@ -1118,7 +1120,8 @@ describe('PeerManager', () => { mockLocalPeer({ identity: webRtcLocalIdentity() }), mockPeerStore(), ) - const initWebRtcConnectionMock = jest.fn() + const initWebRtcConnectionMock = + jest.fn<(peer: Peer, initiator: boolean) => WebRtcConnection>() pm['initWebRtcConnection'] = initWebRtcConnectionMock const { peer, connection } = getConnectedPeer(pm, webRtcCannotInitiateIdentity()) @@ -1142,7 +1145,8 @@ describe('PeerManager', () => { mockLocalPeer({ identity: webRtcLocalIdentity() }), mockPeerStore(), ) - const initWebRtcConnectionMock = jest.fn() + const initWebRtcConnectionMock = + jest.fn<(peer: Peer, initiator: boolean) => WebRtcConnection>() pm['initWebRtcConnection'] = initWebRtcConnectionMock const { peer, connection } = getConnectedPeer(pm, webRtcCanInitiateIdentity()) @@ -1184,7 +1188,7 @@ describe('PeerManager', () => { peer1.onMessage.emit(message, peer1Connection) const reply = new DisconnectingMessage({ - disconnectUntil: expect.any(Number), + disconnectUntil: expect.any(Number) as unknown as number, reason: DisconnectingReason.Congested, sourceIdentity: pm.localPeer.publicIdentity, destinationIdentity: webRtcCanInitiateIdentity(), @@ -1286,7 +1290,7 @@ describe('PeerManager', () => { peer1.onMessage.emit(message, peer1Connection) const reply = new DisconnectingMessage({ - disconnectUntil: expect.any(Number), + disconnectUntil: expect.any(Number) as unknown as number, reason: DisconnectingReason.Congested, sourceIdentity: pm.localPeer.publicIdentity, destinationIdentity: webRtcCannotInitiateIdentity(), diff --git a/ironfish/src/network/testUtilities/helpers.ts b/ironfish/src/network/testUtilities/helpers.ts index 5aad6a6622..06bfc7d9f1 100644 --- a/ironfish/src/network/testUtilities/helpers.ts +++ b/ironfish/src/network/testUtilities/helpers.ts @@ -2,6 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ +import type { SpiedFunction } from 'jest-mock' import { Assert } from '../../assert' import { Identity, isIdentity } from '../identity' import { GetBlockHeadersResponse } from '../messages/getBlockHeaders' @@ -91,7 +92,7 @@ export const getConnectedPeersWithSpies = ( count: number, ): { peer: Peer - sendSpy: jest.SpyInstance + sendSpy: SpiedFunction<(message: NetworkMessage) => Connection | null> }[] => { return [...Array(count)].map((_) => { const { peer } = getConnectedPeer(peerManager) diff --git a/ironfish/src/network/transactionFetcher.test.ts b/ironfish/src/network/transactionFetcher.test.ts index 86d906eea5..6e3d96ce48 100644 --- a/ironfish/src/network/transactionFetcher.test.ts +++ b/ironfish/src/network/transactionFetcher.test.ts @@ -51,7 +51,7 @@ describe('TransactionFetcher', () => { expect(sentPeers).toHaveLength(1) expect(sentPeers[0].sendSpy).toHaveBeenCalledWith( - new PooledTransactionsRequest([hash], expect.any(Number)), + new PooledTransactionsRequest([hash], expect.any(Number) as unknown as number), ) await peerNetwork.stop() diff --git a/ironfish/src/rpc/routes/faucet/getFunds.test.ts b/ironfish/src/rpc/routes/faucet/getFunds.test.ts index df055379ca..8eab7589a0 100644 --- a/ironfish/src/rpc/routes/faucet/getFunds.test.ts +++ b/ironfish/src/rpc/routes/faucet/getFunds.test.ts @@ -25,7 +25,9 @@ describe('Route faucet.getFunds', () => { it('returns a 200 status code', async () => { routeTest.node.config.set('getFundsApi', 'foo.com') - axios.post = jest.fn().mockImplementationOnce(() => Promise.resolve({ data: { id: 5 } })) + axios.post = jest + .fn() + .mockResolvedValueOnce({ data: { id: 5 } }) as typeof axios.post const response = await routeTest.client .request('faucet/getFunds', { @@ -46,7 +48,7 @@ describe('Route faucet.getFunds', () => { describe('when too many faucet requests have been made', () => { it('throws an error', async () => { - axios.post = jest.fn().mockImplementationOnce(() => { + axios.post = jest.fn().mockImplementationOnce(() => { throw { response: { data: { @@ -55,7 +57,7 @@ describe('Route faucet.getFunds', () => { }, }, } - }) + }) as typeof axios.post await expect( routeTest.client.faucet.getFunds({ account: accountName, email }), ).rejects.toThrow(RpcRequestError) @@ -65,7 +67,9 @@ describe('Route faucet.getFunds', () => { describe('when the API request fails', () => { it('throws an error', async () => { const apiResponse = new Error('API failure') as AxiosError - axios.post = jest.fn().mockRejectedValueOnce(apiResponse) + axios.post = jest + .fn() + .mockRejectedValueOnce(apiResponse) as typeof axios.post await expect( routeTest.client.faucet.getFunds({ account: accountName, email }), ).rejects.toThrow('API failure') diff --git a/ironfish/src/rpc/routes/node/stopNode.test.ts b/ironfish/src/rpc/routes/node/stopNode.test.ts index c583f84a88..00107f4d49 100644 --- a/ironfish/src/rpc/routes/node/stopNode.test.ts +++ b/ironfish/src/rpc/routes/node/stopNode.test.ts @@ -7,7 +7,7 @@ describe('Route node.getStatus', () => { const routeTest = createRouteTest() it('should get status', async () => { - routeTest.node.shutdown = jest.fn() + routeTest.node.shutdown = jest.fn<() => Promise>() const response = await routeTest.client.node.stopNode() expect(response.status).toBe(200) diff --git a/ironfish/src/sdk.test.ts b/ironfish/src/sdk.test.ts index f8d5900d7b..a12f52b19c 100644 --- a/ironfish/src/sdk.test.ts +++ b/ironfish/src/sdk.test.ts @@ -285,7 +285,7 @@ describe('IronfishSdk', () => { expect(connect).toHaveBeenCalledTimes(1) expect(client).toBeInstanceOf(RpcIpcClient) - expect(client).toMatchObject(sdk.client) + expect(client).toEqual(sdk.client) }) }) @@ -303,7 +303,7 @@ describe('IronfishSdk', () => { expect(connect).toHaveBeenCalledTimes(1) expect(client).toBeInstanceOf(RpcTcpClient) - expect(client).toMatchObject(sdk.client) + expect(client).toEqual(sdk.client) }) }) }) diff --git a/ironfish/src/storage/database.test.ts b/ironfish/src/storage/database.test.ts index 4da8396fbf..0935bf7e98 100644 --- a/ironfish/src/storage/database.test.ts +++ b/ironfish/src/storage/database.test.ts @@ -167,9 +167,9 @@ describe('Database', () => { const clearRange = StorageUtils.getPrefixKeyRange(Buffer.from('2')) - expect(await testStore.getAllKeys()).toMatchObject(['1', '2a', '2b', '3']) + expect(await testStore.getAllKeys()).toEqual(['1', '2a', '2b', '3']) await testStore.clear(undefined, clearRange) - expect(await testStore.getAllKeys()).toMatchObject(['1', '3']) + expect(await testStore.getAllKeys()).toEqual(['1', '3']) }) it('should clear store in a transaction', async () => { @@ -205,9 +205,9 @@ describe('Database', () => { const clearRange = StorageUtils.getPrefixKeyRange(Buffer.from('2')) - await expect(testStore.getAllKeys(tx)).resolves.toMatchObject(['1', '2a', '2b', '3']) + await expect(testStore.getAllKeys(tx)).resolves.toEqual(['1', '2a', '2b', '3']) await testStore.clear(tx, clearRange) - await expect(testStore.getAllKeys(tx)).resolves.toMatchObject(['1', '3']) + await expect(testStore.getAllKeys(tx)).resolves.toEqual(['1', '3']) }) }) @@ -617,8 +617,8 @@ describe('Database', () => { await db.metaStore.put('c', 1002) await db.metaStore.put('d', 1003) - await expect(db.metaStore.getAllKeys()).resolves.toMatchObject(['a', 'b', 'c', 'd']) - await expect(db.metaStore.getAllValues()).resolves.toMatchObject([1000, 1001, 1002, 1003]) + await expect(db.metaStore.getAllKeys()).resolves.toEqual(['a', 'b', 'c', 'd']) + await expect(db.metaStore.getAllValues()).resolves.toEqual([1000, 1001, 1002, 1003]) }) it('should get all keys and values in a range', async () => { @@ -635,14 +635,14 @@ describe('Database', () => { gte: Buffer.from('b'), lt: Buffer.from('d'), }), - ).resolves.toMatchObject([1001, 1002]) + ).resolves.toEqual([1001, 1002]) await expect( db.metaStore.getAllKeys(undefined, { gte: Buffer.from('b'), lt: Buffer.from('d'), }), - ).resolves.toMatchObject(['b', 'c']) + ).resolves.toEqual(['b', 'c']) }) it('should encode and decode keys', async () => { @@ -759,27 +759,27 @@ describe('Database', () => { await db.transaction(async (tx) => { await expect( db.metaStore.getAllKeys(tx, undefined, { ordered: true }), - ).resolves.toMatchObject(['a', 'b', 'd', 'e']) + ).resolves.toEqual(['a', 'b', 'd', 'e']) await expect( db.metaStore.getAllValues(tx, undefined, { ordered: true }), - ).resolves.toMatchObject([1001, 1003, 1002, 1000]) + ).resolves.toEqual([1001, 1003, 1002, 1000]) await db.metaStore.put('a', 1004, tx) await db.metaStore.put('c', 999, tx) await expect( db.metaStore.getAllKeys(tx, undefined, { ordered: true }), - ).resolves.toMatchObject(['a', 'b', 'c', 'd', 'e']) + ).resolves.toEqual(['a', 'b', 'c', 'd', 'e']) await expect( db.metaStore.getAllValues(tx, undefined, { ordered: true }), - ).resolves.toMatchObject([1004, 1003, 999, 1002, 1000]) + ).resolves.toEqual([1004, 1003, 999, 1002, 1000]) await expect( db.metaStore.getAllKeys(tx, undefined, { ordered: true, reverse: true }), - ).resolves.toMatchObject(['e', 'd', 'c', 'b', 'a']) + ).resolves.toEqual(['e', 'd', 'c', 'b', 'a']) await expect( db.metaStore.getAllValues(tx, undefined, { ordered: true, reverse: true }), - ).resolves.toMatchObject([1000, 1002, 999, 1003, 1004]) + ).resolves.toEqual([1000, 1002, 999, 1003, 1004]) }) }) }) diff --git a/ironfish/src/storage/database/encoding.test.ts b/ironfish/src/storage/database/encoding.test.ts index d1df25a8d9..bf208c074c 100644 --- a/ironfish/src/storage/database/encoding.test.ts +++ b/ironfish/src/storage/database/encoding.test.ts @@ -109,38 +109,38 @@ describe('Encoding', () => { await expect(prefixStore.get(['b', 'b'])).resolves.toBe('b') // Iteration operations - await expect(prefixStore.getAllValues()).resolves.toMatchObject(['a', 'b']) - await expect(prefixStore.getAllKeys()).resolves.toMatchObject([ + await expect(prefixStore.getAllValues()).resolves.toEqual(['a', 'b']) + await expect(prefixStore.getAllKeys()).resolves.toEqual([ ['a', 'a'], ['b', 'b'], ]) - await expect(prefixStore.getAllValues(undefined, keyRangeA)).resolves.toMatchObject(['a']) - await expect(prefixStore.getAllValues(undefined, keyRangeB)).resolves.toMatchObject(['b']) + await expect(prefixStore.getAllValues(undefined, keyRangeA)).resolves.toEqual(['a']) + await expect(prefixStore.getAllValues(undefined, keyRangeB)).resolves.toEqual(['b']) await prefixStore.clear(undefined, keyRangeA) await expect(prefixStore.get(['a', 'a'])).resolves.toBe(undefined) await expect(prefixStore.get(['b', 'b'])).resolves.toBe('b') - await expect(prefixStore.getAllValues(undefined, keyRangeA)).resolves.toMatchObject([]) - await expect(prefixStore.getAllValues(undefined, keyRangeB)).resolves.toMatchObject(['b']) + await expect(prefixStore.getAllValues(undefined, keyRangeA)).resolves.toEqual([]) + await expect(prefixStore.getAllValues(undefined, keyRangeB)).resolves.toEqual(['b']) await prefixStore.clear(undefined, keyRangeB) // Now try transactions await db.transaction(async (tx) => { await prefixStore.put(['a', 'a'], 'a', tx) - await expect(prefixStore.getAllValues(tx, keyRangeA)).resolves.toMatchObject(['a']) + await expect(prefixStore.getAllValues(tx, keyRangeA)).resolves.toEqual(['a']) await prefixStore.clear(tx, keyRangeA) - await expect(prefixStore.getAllValues(tx, keyRangeA)).resolves.toMatchObject([]) + await expect(prefixStore.getAllValues(tx, keyRangeA)).resolves.toEqual([]) await prefixStore.put(['b', 'b'], 'b', tx) - await expect(prefixStore.getAllValues(tx, keyRangeB)).resolves.toMatchObject(['b']) + await expect(prefixStore.getAllValues(tx, keyRangeB)).resolves.toEqual(['b']) await prefixStore.clear(tx, keyRangeB) - await expect(prefixStore.getAllValues(tx, keyRangeB)).resolves.toMatchObject([]) + await expect(prefixStore.getAllValues(tx, keyRangeB)).resolves.toEqual([]) }) - await expect(prefixStore.getAllValues(undefined, keyRangeA)).resolves.toMatchObject([]) - await expect(prefixStore.getAllValues(undefined, keyRangeB)).resolves.toMatchObject([]) + await expect(prefixStore.getAllValues(undefined, keyRangeA)).resolves.toEqual([]) + await expect(prefixStore.getAllValues(undefined, keyRangeB)).resolves.toEqual([]) }) it('should error with incorrect prefix size', async () => { diff --git a/ironfish/src/syncer.test.ts b/ironfish/src/syncer.test.ts index 4b0f2a82d4..9733840833 100644 --- a/ironfish/src/syncer.test.ts +++ b/ironfish/src/syncer.test.ts @@ -113,7 +113,7 @@ describe('Syncer', () => { const syncFromSpy = jest.spyOn(syncer, 'syncFrom') const [promise, , reject] = PromiseUtils.split() - syncFromSpy.mockResolvedValue(promise) + syncFromSpy.mockReturnValue(promise) syncer['startSync'](peer) expect(syncer.stopping).not.toBe(null) @@ -143,7 +143,7 @@ describe('Syncer', () => { const syncFromSpy = jest.spyOn(syncer, 'syncFrom') const [promise, resolve] = PromiseUtils.split() - syncFromSpy.mockResolvedValue(promise) + syncFromSpy.mockReturnValue(promise) syncer['startSync'](peer) expect(syncer.stopping).not.toBe(null) @@ -264,7 +264,7 @@ describe('Syncer', () => { const syncFromSpy = jest.spyOn(syncer, 'syncFrom') const [promise, resolve] = PromiseUtils.split() - syncFromSpy.mockResolvedValue(promise) + syncFromSpy.mockReturnValue(promise) syncer['startSync'](peer) // Set the nextMeasureTime to be less than now, which is the trigger to diff --git a/ironfish/src/telemetry/telemetry.test.ts b/ironfish/src/telemetry/telemetry.test.ts index 6e42e4cdac..38c19bfd5f 100644 --- a/ironfish/src/telemetry/telemetry.test.ts +++ b/ironfish/src/telemetry/telemetry.test.ts @@ -86,7 +86,9 @@ describe('Telemetry', () => { const points = telemetry['points'] expect(points).toHaveLength(currentPointsLength + 1) - expect(points[points.length - 1]).toMatchObject(mockMetric) + expect(points[points.length - 1]).toMatchObject( + mockMetric as unknown as Record, + ) }) }) diff --git a/ironfish/src/testHarness.ts b/ironfish/src/testHarness.ts new file mode 100644 index 0000000000..f89eb8062d --- /dev/null +++ b/ironfish/src/testHarness.ts @@ -0,0 +1,25 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ +import type { Jest } from '@jest/environment' +import type { JestExpect } from '@jest/expect' +import type { Global } from '@jest/types' + +declare global { + const { + it, + test, + fit, + xit, + xtest, + describe, + xdescribe, + fdescribe, + beforeAll, + beforeEach, + afterEach, + afterAll, + }: Global.GlobalAdditions + const expect: JestExpect + const jest: Jest +} diff --git a/ironfish/src/testUtilities/matchers/blockchain.ts b/ironfish/src/testUtilities/matchers/blockchain.ts index 51df5c1209..08c770cc39 100644 --- a/ironfish/src/testUtilities/matchers/blockchain.ts +++ b/ironfish/src/testUtilities/matchers/blockchain.ts @@ -2,6 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ +import type { AsyncExpectationResult, SyncExpectationResult } from 'expect' import { diff } from 'jest-diff' import { Blockchain } from '../../blockchain' import { Block } from '../../primitives/block' @@ -12,7 +13,7 @@ import { makeError, makeResult } from './utils' function toEqualHash( self: BlockHash | null | undefined, other: BlockHash | null | undefined, -): jest.CustomMatcherResult { +): SyncExpectationResult { let error: string | null = null if (!self || !other) { @@ -26,7 +27,7 @@ function toEqualHash( return makeError(error, `Expected two serde elements to match, but they didn't`) } -function toEqualNullifier(self: Nullifier, other: Nullifier): jest.CustomMatcherResult { +function toEqualNullifier(self: Nullifier, other: Nullifier): SyncExpectationResult { let error: string | null = null if (!self || !other) { @@ -40,7 +41,7 @@ function toEqualNullifier(self: Nullifier, other: Nullifier): jest.CustomMatcher return makeError(error, `Expected two serde elements to match, but they didn't`) } -async function toAddBlock(self: Blockchain, other: Block): Promise { +async function toAddBlock(self: Blockchain, other: Block): AsyncExpectationResult { const result = await self.addBlock(other) if (!result.isAdded) { @@ -50,10 +51,7 @@ async function toAddBlock(self: Blockchain, other: Block): Promise { +async function toAddDoubleSpendBlock(self: Blockchain, other: Block): AsyncExpectationResult { // Mock data stores to allow creation of a double spend chain const transactionHashMock = jest .spyOn(self, 'transactionHashHasBlock') @@ -83,13 +81,12 @@ expect.extend({ toAddDoubleSpendBlock: toAddDoubleSpendBlock, }) -declare global { - namespace jest { - interface Matchers { - toEqualNullifier(other: Nullifier): R - toEqualHash(other: BlockHash | null | undefined): R - toAddBlock(block: Block): Promise - toAddDoubleSpendBlock(block: Block): Promise - } +declare module 'expect' { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + interface Matchers, T = unknown> { + toEqualNullifier(other: Nullifier): R + toEqualHash(other: BlockHash | null | undefined): R + toAddBlock(block: Block): Promise + toAddDoubleSpendBlock(block: Block): Promise } } diff --git a/ironfish/src/testUtilities/matchers/buffer.ts b/ironfish/src/testUtilities/matchers/buffer.ts index 7e9caa4664..f5f20adee8 100644 --- a/ironfish/src/testUtilities/matchers/buffer.ts +++ b/ironfish/src/testUtilities/matchers/buffer.ts @@ -2,13 +2,14 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ +import type { SyncExpectationResult } from 'expect' import { diff } from 'jest-diff' import { makeResult } from './utils' function toEqualBuffer( self: Buffer | null | undefined, other: Buffer | null | undefined, -): jest.CustomMatcherResult { +): SyncExpectationResult { const pass = self === other || (!self && !other) || (self && other && self.equals(other)) if (!pass) { @@ -28,10 +29,9 @@ function toEqualBuffer( expect.extend({ toEqualBuffer: toEqualBuffer }) -declare global { - namespace jest { - interface Matchers { - toEqualBuffer(other: Buffer | null | undefined): R - } +declare module 'expect' { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + interface Matchers, T = unknown> { + toEqualBuffer(other: Buffer | null | undefined): R } } diff --git a/ironfish/src/testUtilities/matchers/merkletree.ts b/ironfish/src/testUtilities/matchers/merkletree.ts index 373f141928..674856b4e3 100644 --- a/ironfish/src/testUtilities/matchers/merkletree.ts +++ b/ironfish/src/testUtilities/matchers/merkletree.ts @@ -2,19 +2,19 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ +import type { AsyncExpectationResult, SyncExpectationResult } from 'expect' import { diff } from 'jest-diff' import { MerkleTree, Witness, WitnessSide } from '../../merkletree' import { NodeValue } from '../../merkletree/schema' import { makeError } from './utils' -declare global { - namespace jest { - interface Matchers { - toHaveLeaves(characters: string, parents: number[]): Promise - toHaveNodes(nodeSpecs: [number, WitnessSide, number, string][]): Promise - toMatchTree(other: MerkleTree): Promise - toMatchWitness(treeSize: number, rootHash: string, authPath: [WitnessSide, string][]): R - } +declare module 'expect' { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + interface Matchers, T = unknown> { + toHaveLeaves(characters: string, parents: number[]): Promise + toHaveNodes(nodeSpecs: [number, WitnessSide, number, string][]): Promise + toMatchTree(other: MerkleTree): Promise + toMatchWitness(treeSize: number, rootHash: string, authPath: [WitnessSide, string][]): R } } @@ -23,7 +23,7 @@ expect.extend({ tree: MerkleTree, characters: string, parents: number[], - ): Promise { + ): AsyncExpectationResult { let error: string | null = null const treeSize = await tree.size() @@ -54,7 +54,7 @@ expect.extend({ async toHaveNodes( tree: MerkleTree, nodeSpecs: [number, WitnessSide, number, string][], - ): Promise { + ): AsyncExpectationResult { let error: string | null = null const treeNodes = await tree.nodes.getAllValues() @@ -105,7 +105,7 @@ expect.extend({ async toMatchTree( tree: MerkleTree, other: MerkleTree, - ): Promise { + ): AsyncExpectationResult { let error: string | null = null const treeLeafCount = await tree.getCount('Leaves') const treeNodeCount = await tree.getCount('Nodes') @@ -152,7 +152,7 @@ expect.extend({ treeSize: number, rootHash: string, authenticationPath: [WitnessSide, string][], - ): jest.CustomMatcherResult { + ): SyncExpectationResult { let error: string | null = null if (witness === undefined) { diff --git a/ironfish/src/testUtilities/matchers/string.ts b/ironfish/src/testUtilities/matchers/string.ts index 67ad51654e..06954ba470 100644 --- a/ironfish/src/testUtilities/matchers/string.ts +++ b/ironfish/src/testUtilities/matchers/string.ts @@ -2,9 +2,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ +import type { SyncExpectationResult } from 'expect' import { makeResult } from './utils' -function toBeBase64(self: string | null | undefined): jest.CustomMatcherResult { +function toBeBase64(self: string | null | undefined): SyncExpectationResult { const pass = !!self && self === Buffer.from(self, 'base64').toString('base64') if (!pass) { @@ -16,10 +17,9 @@ function toBeBase64(self: string | null | undefined): jest.CustomMatcherResult { expect.extend({ toBeBase64 }) -declare global { - namespace jest { - interface Matchers { - toBeBase64(): R - } +declare module 'expect' { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + interface Matchers, T = unknown> { + toBeBase64(): R } } diff --git a/ironfish/src/testUtilities/mocks.ts b/ironfish/src/testUtilities/mocks.ts index a39ea31c6d..9f37deb686 100644 --- a/ironfish/src/testUtilities/mocks.ts +++ b/ironfish/src/testUtilities/mocks.ts @@ -30,7 +30,7 @@ export function mockWallet(): any { export function mockVerifier(): any { return { - verifyNewTransaction: jest.fn().mockResolvedValue({}), + verifyNewTransaction: jest.fn<(...args: any[]) => Promise>().mockResolvedValue({}), } } @@ -107,6 +107,6 @@ export function mockWorkerPool(): any { export function mockConfig(values: Record): any { return { - get: jest.fn((x) => values[x]), + get: jest.fn((x: string) => values[x]), } } diff --git a/ironfish/src/testUtilities/utils.test.ts b/ironfish/src/testUtilities/utils.test.ts deleted file mode 100644 index 75438d67b5..0000000000 --- a/ironfish/src/testUtilities/utils.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ - -import { mockImplementationShuffle } from './utils' - -describe('Mocks', () => { - it('should shuffle mock', async () => { - const mock = jest.fn() - - const results: number[] = [] - - mockImplementationShuffle<[number], void>(mock, (value: number) => { - results.push(value) - return Promise.resolve() - }) - - const promises = [] - for (let i = 0; i < 10; ++i) { - promises.push(mock(i)) - } - await Promise.all(promises) - - expect(results).toHaveLength(10) - }) - - it('should allow cancelation', () => { - jest.useFakeTimers() - - const mock = jest.fn() - const results: number[] = [] - - function mockImplementation(value: number) { - results.push(value) - return Promise.resolve(value) - } - - // it should have the result from the shuffled result - mockImplementationShuffle(mock, mockImplementation, 1) - mock(0) - jest.runAllTimers() - expect(results).toHaveLength(1) - - results.length = 0 - - // when we call cancel it should not have the result - const cancelShuffle = mockImplementationShuffle(mock, mockImplementation, 1) - mock(0) - cancelShuffle() - jest.runAllTimers() - expect(results).toHaveLength(0) - }) -}) diff --git a/ironfish/src/testUtilities/utils.ts b/ironfish/src/testUtilities/utils.ts index dc8f961bff..9deb2e1c84 100644 --- a/ironfish/src/testUtilities/utils.ts +++ b/ironfish/src/testUtilities/utils.ts @@ -66,67 +66,3 @@ export async function splitNotes( Assert.isNotNull(account.spendingKey) return transaction.post(account.spendingKey) } - -/** - * Asserts the type of a given function as a Jest mock. - */ -export function typeMock( - func: (...args: [...T]) => R, -): jest.Mock { - return func as jest.Mock -} - -/** - * Used to shuffle the responses from an asynchronous API call using a debounce strategy. - * @param mock The mock to intercept calls for and shuffle - * @param mocked The mock function to replace mock with - * @param time The maximum amount of debounce time to allow before returning shuffled results - */ -export function mockImplementationShuffle( - mock: jest.Mock, TArgs>, - mocked: (...args: TArgs) => Promise, - time = 10, -): () => void { - type PromiseResolve = (result: Promise) => void - const buffer: [TArgs, PromiseResolve][] = [] - let lastTimeout: number | null = null - let lastSend: number | null = null - - mock.mockImplementation((...args: TArgs): Promise => { - const promise = new Promise>((resolve) => { - if (lastTimeout) { - clearTimeout(lastTimeout) - } - - buffer.push([args, resolve]) - - function send() { - lastSend = Date.now() - - const shuffled = buffer.slice().sort(() => Math.random() - 0.5) - buffer.length = 0 - - for (const [args, resolve] of shuffled) { - resolve(mocked(...args)) - } - } - - // Force a send if the maximum amount of time has elapsed - if (lastSend !== null && Date.now() - lastSend > time) { - send() - return - } - - // Start the debounce timer - lastTimeout = setTimeout(send, time) as unknown as number - }) - - return promise.then((r) => r) - }) - - return () => { - if (lastTimeout) { - clearTimeout(lastTimeout) - } - } -} diff --git a/ironfish/src/utils/retry.test.ts b/ironfish/src/utils/retry.test.ts index 6d36ca0e91..f68388e81a 100644 --- a/ironfish/src/utils/retry.test.ts +++ b/ironfish/src/utils/retry.test.ts @@ -10,7 +10,7 @@ describe('Retry', () => { jest.useFakeTimers({ legacyFakeTimers: false }) it('immediately returns when there is no error', async () => { - const fn = jest.fn().mockResolvedValue(123) + const fn = jest.fn<() => Promise>().mockResolvedValue(123) const retry = new Retry({ delay: 1000, jitter: 0.2, @@ -23,7 +23,7 @@ describe('Retry', () => { describe('without maxRetries', () => { it('keeps retrying until the function succeeds', async () => { - const fn = jest.fn() + const fn = jest.fn<() => Promise>() const retry = new Retry({ delay: 1000, jitter: 0.2, @@ -53,7 +53,7 @@ describe('Retry', () => { describe('with maxRetries', () => { it('keeps retrying until the maximum number of retries is reached', async () => { const maxRetries = 0 //10 - const fn = jest.fn() + const fn = jest.fn<() => Promise>() const retry = new Retry({ delay: 1000, jitter: 0.2, diff --git a/ironfish/src/wallet/scanner/noteDecryptor.test.ts b/ironfish/src/wallet/scanner/noteDecryptor.test.ts index d40b2c9775..c3490595cb 100644 --- a/ironfish/src/wallet/scanner/noteDecryptor.test.ts +++ b/ironfish/src/wallet/scanner/noteDecryptor.test.ts @@ -50,10 +50,7 @@ describe('BackgroundNoteDecryptor', () => { decryptor.start() - const callback = jest.fn< - ReturnType, - jest.ArgumentsOf - >() + const callback = jest.fn() for (const block of blocks) { await decryptor.decryptNotesFromBlock( diff --git a/ironfish/src/wallet/scanner/remoteChainProcessor.test.ts b/ironfish/src/wallet/scanner/remoteChainProcessor.test.ts index 78a385b128..dae7a3f897 100644 --- a/ironfish/src/wallet/scanner/remoteChainProcessor.test.ts +++ b/ironfish/src/wallet/scanner/remoteChainProcessor.test.ts @@ -2,6 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ +import type { Mock } from 'jest-mock' import { BlockHeader } from '../../primitives' import { ALL_API_NAMESPACES, RpcMemoryClient } from '../../rpc' import { createNodeTest, useMinerBlockFixture } from '../../testUtilities' @@ -46,7 +47,7 @@ describe('RemoteChainProcessor', () => { maxQueueSize: 10, }) - const onEvent: jest.Mock = jest.fn() + const onEvent: Mock<(header: BlockHeader, event: 'add' | 'remove') => void> = jest.fn() processor.onAdd.on((block) => onEvent(block.header, 'add')) processor.onRemove.on((block) => onEvent(block.header, 'remove')) @@ -101,7 +102,7 @@ describe('RemoteChainProcessor', () => { maxQueueSize: 10, }) - const onEvent: jest.Mock = jest.fn() + const onEvent: Mock<(header: BlockHeader, event: 'add' | 'remove') => void> = jest.fn() processor.onAdd.on((block) => onEvent(block.header, 'add')) processor.onRemove.on((block) => onEvent(block.header, 'remove')) diff --git a/ironfish/src/wallet/wallet.test.slow.ts b/ironfish/src/wallet/wallet.test.slow.ts index 9aa371f52e..754c7ac025 100644 --- a/ironfish/src/wallet/wallet.test.slow.ts +++ b/ironfish/src/wallet/wallet.test.slow.ts @@ -1,6 +1,7 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ +import type { SpiedFunction } from 'jest-mock' import { Asset, ASSET_ID_LENGTH, generateKey, multisig } from '@ironfish/rust-nodejs' import { Assert } from '../assert' import { Transaction } from '../primitives' @@ -20,8 +21,8 @@ import { AssertMultisigSigner } from '../wallet' describe('Wallet', () => { const nodeTest = createNodeTest() - let targetMeetsSpy: jest.SpyInstance - let targetSpy: jest.SpyInstance + let targetMeetsSpy: SpiedFunction + let targetSpy: SpiedFunction beforeAll(async () => { targetMeetsSpy = jest.spyOn(Target, 'meets').mockImplementation(() => true) diff --git a/ironfish/src/wallet/wallet.test.ts b/ironfish/src/wallet/wallet.test.ts index 79202b7135..71e3357ad8 100644 --- a/ironfish/src/wallet/wallet.test.ts +++ b/ironfish/src/wallet/wallet.test.ts @@ -2059,7 +2059,7 @@ describe('Wallet', () => { ).toEqual(AssetStatus.UNCONFIRMED) // Remove the head and check status - jest.spyOn(account, 'getHead').mockResolvedValueOnce(Promise.resolve(null)) + jest.spyOn(account, 'getHead').mockResolvedValueOnce(null) expect(await node.wallet.getAssetStatus(account, assetValue)).toEqual(AssetStatus.UNKNOWN) }) }) diff --git a/ironfish/src/workerPool/tasks/submitTelemetry.test.ts b/ironfish/src/workerPool/tasks/submitTelemetry.test.ts index a45bcf36b1..9d35b67ca7 100644 --- a/ironfish/src/workerPool/tasks/submitTelemetry.test.ts +++ b/ironfish/src/workerPool/tasks/submitTelemetry.test.ts @@ -65,9 +65,7 @@ describe('SubmitTelemetryResponse', () => { describe('SubmitTelemetryTask', () => { describe('execute', () => { it('submits points to the API', async () => { - const submitTelemetryPointsToApi = jest - .spyOn(axios, 'post') - .mockImplementationOnce(jest.fn()) + const submitTelemetryPointsToApi = jest.spyOn(axios, 'post').mockResolvedValueOnce(null) const mockMetric: Metric = { measurement: 'node', fields: [ diff --git a/package.json b/package.json index a19c52affb..32b5f045d1 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,6 @@ "coverage:upload": "lerna exec '\"yarn codecov -t $CODECOV_TOKEN -f ./coverage/clover.xml -F $LERNA_PACKAGE_NAME -p $ROOT_PATH/ --disable=gcov\"'" }, "devDependencies": { - "@types/jest": "29.5.8", "@typescript-eslint/eslint-plugin": "6.19.0", "@typescript-eslint/parser": "6.19.0", "codecov": "3.8.3", diff --git a/yarn.lock b/yarn.lock index 38709b4636..b94a91a5a6 100644 --- a/yarn.lock +++ b/yarn.lock @@ -511,13 +511,6 @@ "@types/node" "*" jest-mock "^29.7.0" -"@jest/expect-utils@^29.3.1": - version "29.3.1" - resolved "https://registry.yarnpkg.com/@jest/expect-utils/-/expect-utils-29.3.1.tgz#531f737039e9b9e27c42449798acb5bba01935b6" - integrity sha512-wlrznINZI5sMjwvUoLVk617ll/UYfGIZNxmbU+Pa7wmkL4vYzhV9R2pwVqUh4NWWuLQWkI8+8mOkxs//prKQ3g== - dependencies: - jest-get-type "^29.2.0" - "@jest/expect-utils@^29.7.0": version "29.7.0" resolved "https://registry.yarnpkg.com/@jest/expect-utils/-/expect-utils-29.7.0.tgz#023efe5d26a8a70f21677d0a1afc0f0a44e3a1c6" @@ -2772,14 +2765,6 @@ dependencies: "@types/istanbul-lib-report" "*" -"@types/jest@29.5.8": - version "29.5.8" - resolved "https://registry.yarnpkg.com/@types/jest/-/jest-29.5.8.tgz#ed5c256fe2bc7c38b1915ee5ef1ff24a3427e120" - integrity sha512-fXEFTxMV2Co8ZF5aYFJv+YeA08RTYJfhtN5c9JSv/mFEMe+xxjufCb+PHL+bJcMs/ebPUsBu+UNTEz+ydXrR6g== - dependencies: - expect "^29.0.0" - pretty-format "^29.0.0" - "@types/json-schema@^7.0.12": version "7.0.13" resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.13.tgz#02c24f4363176d2d18fc8b70b9f3c54aba178a85" @@ -4743,11 +4728,6 @@ dezalgo@^1.0.0: asap "^2.0.0" wrappy "1" -diff-sequences@^29.3.1: - version "29.3.1" - resolved "https://registry.yarnpkg.com/diff-sequences/-/diff-sequences-29.3.1.tgz#104b5b95fe725932421a9c6e5b4bef84c3f2249e" - integrity sha512-hlM3QR272NXCi4pq+N4Kok4kOp6EsgOM3ZSpJI7Da3UAs+Ttsi8MRmB6trM/lhyzUxGfOgnpkHtgqm5Q/CTcfQ== - diff-sequences@^29.6.3: version "29.6.3" resolved "https://registry.yarnpkg.com/diff-sequences/-/diff-sequences-29.6.3.tgz#4deaf894d11407c51efc8418012f9e70b84ea921" @@ -5233,17 +5213,6 @@ expand-template@^2.0.3: resolved "https://registry.yarnpkg.com/expand-template/-/expand-template-2.0.3.tgz#6e14b3fcee0f3a6340ecb57d2e8918692052a47c" integrity sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg== -expect@^29.0.0: - version "29.3.1" - resolved "https://registry.yarnpkg.com/expect/-/expect-29.3.1.tgz#92877aad3f7deefc2e3f6430dd195b92295554a6" - integrity sha512-gGb1yTgU30Q0O/tQq+z30KBWv24ApkMgFUpvKBkyLUBL68Wv8dHdJxTBZFl/iT8K/bqDHvUYRH6IIN3rToopPA== - dependencies: - "@jest/expect-utils" "^29.3.1" - jest-get-type "^29.2.0" - jest-matcher-utils "^29.3.1" - jest-message-util "^29.3.1" - jest-util "^29.3.1" - expect@^29.7.0: version "29.7.0" resolved "https://registry.yarnpkg.com/expect/-/expect-29.7.0.tgz#578874590dcb3214514084c08115d8aee61e11bc" @@ -6719,16 +6688,6 @@ jest-config@^29.7.0: slash "^3.0.0" strip-json-comments "^3.1.1" -jest-diff@^29.3.1: - version "29.3.1" - resolved "https://registry.yarnpkg.com/jest-diff/-/jest-diff-29.3.1.tgz#d8215b72fed8f1e647aed2cae6c752a89e757527" - integrity sha512-vU8vyiO7568tmin2lA3r2DP8oRvzhvRcD4DjpXc6uGveQodyk7CKLhQlCSiwgx3g0pFaE88/KLZ0yaTWMc4Uiw== - dependencies: - chalk "^4.0.0" - diff-sequences "^29.3.1" - jest-get-type "^29.2.0" - pretty-format "^29.3.1" - jest-diff@^29.7.0: version "29.7.0" resolved "https://registry.yarnpkg.com/jest-diff/-/jest-diff-29.7.0.tgz#017934a66ebb7ecf6f205e84699be10afd70458a" @@ -6769,11 +6728,6 @@ jest-environment-node@^29.7.0: jest-mock "^29.7.0" jest-util "^29.7.0" -jest-get-type@^29.2.0: - version "29.2.0" - resolved "https://registry.yarnpkg.com/jest-get-type/-/jest-get-type-29.2.0.tgz#726646f927ef61d583a3b3adb1ab13f3a5036408" - integrity sha512-uXNJlg8hKFEnDgFsrCjznB+sTxdkuqiCL6zMgA75qEbAJjJYTs9XPrvDctrEig2GDow22T/LvHgO57iJhXB/UA== - jest-get-type@^29.6.3: version "29.6.3" resolved "https://registry.yarnpkg.com/jest-get-type/-/jest-get-type-29.6.3.tgz#36f499fdcea197c1045a127319c0481723908fd1" @@ -6848,16 +6802,6 @@ jest-leak-detector@^29.7.0: jest-get-type "^29.6.3" pretty-format "^29.7.0" -jest-matcher-utils@^29.3.1: - version "29.3.1" - resolved "https://registry.yarnpkg.com/jest-matcher-utils/-/jest-matcher-utils-29.3.1.tgz#6e7f53512f80e817dfa148672bd2d5d04914a572" - integrity sha512-fkRMZUAScup3txIKfMe3AIZZmPEjWEdsPJFK3AIy5qRohWqQFg1qrmKfYXR9qEkNc7OdAu2N4KPHibEmy4HPeQ== - dependencies: - chalk "^4.0.0" - jest-diff "^29.3.1" - jest-get-type "^29.2.0" - pretty-format "^29.3.1" - jest-matcher-utils@^29.7.0: version "29.7.0" resolved "https://registry.yarnpkg.com/jest-matcher-utils/-/jest-matcher-utils-29.7.0.tgz#ae8fec79ff249fd592ce80e3ee474e83a6c44f12" @@ -8962,7 +8906,7 @@ pretty-bytes@^5.3.0: resolved "https://registry.yarnpkg.com/pretty-bytes/-/pretty-bytes-5.6.0.tgz#356256f643804773c82f64723fe78c92c62beaeb" integrity sha512-FFw039TmrBqFK8ma/7OL3sDz/VytdtJr044/QUJtH0wK9lb9jLq9tJyIxUwtQJHwar2BqtiA4iCWSwo9JLkzFg== -pretty-format@^29.0.0, pretty-format@^29.3.1: +pretty-format@^29.3.1: version "29.3.1" resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-29.3.1.tgz#1841cac822b02b4da8971dacb03e8a871b4722da" integrity sha512-FyLnmb1cYJV8biEIiRyzRFvs2lry7PPIvOqKVe1GCUEYg4YGmlx1qG9EJNMxArYm7piII4qb8UV1Pncq5dxmcg==