Skip to content

Commit

Permalink
Remove @types/jest, and use Jest's own type annotations instead
Browse files Browse the repository at this point in the history
  • Loading branch information
andiflabs committed Jul 11, 2024
1 parent 846f90d commit 8c16d8d
Show file tree
Hide file tree
Showing 40 changed files with 220 additions and 302 deletions.
25 changes: 25 additions & 0 deletions ironfish-cli/src/testHarness.ts
Original file line number Diff line number Diff line change
@@ -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
}
7 changes: 4 additions & 3 deletions ironfish-cli/src/utils/chainport/utils.test.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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', () => {
Expand All @@ -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,
Expand Down Expand Up @@ -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: [
Expand Down
1 change: 0 additions & 1 deletion ironfish-rust-nodejs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
25 changes: 25 additions & 0 deletions ironfish-rust-nodejs/tests/testHarness.ts
Original file line number Diff line number Diff line change
@@ -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
}
1 change: 0 additions & 1 deletion ironfish/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
3 changes: 2 additions & 1 deletion ironfish/src/assets/assetsVerifier.test.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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
}
Expand Down
9 changes: 5 additions & 4 deletions ironfish/src/chainProcessor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -32,7 +33,7 @@ describe('ChainProcessor', () => {
head: chain.genesis.hash,
})

const onEvent: jest.Mock<void, [BlockHeader, 'add' | 'remove']> = 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'))

Expand Down Expand Up @@ -82,7 +83,7 @@ describe('ChainProcessor', () => {
head: chain.genesis.hash,
})

const onEvent: jest.Mock<void, [BlockHeader, 'add' | 'remove']> = 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'))

Expand Down Expand Up @@ -149,7 +150,7 @@ describe('ChainProcessor', () => {

expect(chain.head.hash).toEqual(block2.header.hash)

const onEvent: jest.Mock<void, [BlockHeader, 'add' | 'remove']> = 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'))
Expand Down Expand Up @@ -178,7 +179,7 @@ describe('ChainProcessor', () => {
await expect(chain).toAddBlock(block)
expect(chain.head.hash).toEqual(block.header.hash)

const onEvent: jest.Mock<void, [BlockHeader, 'add' | 'remove']> = 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'))
Expand Down
2 changes: 1 addition & 1 deletion ironfish/src/event.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
13 changes: 7 additions & 6 deletions ironfish/src/genesis/genesis.test.slow.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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<typeof Target.meets>
let targetSpy: SpiedFunction<typeof Target.calculateTarget>

beforeAll(() => {
targetMeetsSpy = jest.spyOn(Target, 'meets').mockImplementation(() => true)
Expand All @@ -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<typeof Target.meets>
let targetSpy: SpiedFunction<typeof Target.calculateTarget>

beforeAll(() => {
targetMeetsSpy = jest.spyOn(Target, 'meets').mockImplementation(() => true)
Expand Down Expand Up @@ -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<typeof Target.meets>
let targetSpy: SpiedFunction<typeof Target.calculateTarget>

beforeAll(() => {
targetMeetsSpy = jest.spyOn(Target, 'meets').mockImplementation(() => true)
Expand Down
4 changes: 3 additions & 1 deletion ironfish/src/memPool/memPool.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 6 additions & 2 deletions ironfish/src/network/blockFetcher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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)
Expand Down
8 changes: 5 additions & 3 deletions ironfish/src/network/peerNetwork.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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(
Expand Down
4 changes: 3 additions & 1 deletion ironfish/src/network/peers/connections/connection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion ironfish/src/network/peers/peer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand Down
18 changes: 11 additions & 7 deletions ironfish/src/network/peers/peerManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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'

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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())
Expand All @@ -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())
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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(),
Expand Down
3 changes: 2 additions & 1 deletion ironfish/src/network/testUtilities/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -91,7 +92,7 @@ export const getConnectedPeersWithSpies = (
count: number,
): {
peer: Peer
sendSpy: jest.SpyInstance<Connection | null, [message: NetworkMessage]>
sendSpy: SpiedFunction<(message: NetworkMessage) => Connection | null>
}[] => {
return [...Array<null>(count)].map((_) => {
const { peer } = getConnectedPeer(peerManager)
Expand Down
Loading

0 comments on commit 8c16d8d

Please sign in to comment.