Skip to content
This repository was archived by the owner on Dec 21, 2021. It is now read-only.

Commit 7c0b343

Browse files
authored
Tests to typescript (#229)
Convert most of tests to TypeScript
1 parent fc9f34d commit 7c0b343

33 files changed

+363
-291
lines changed

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,8 @@
4545
"coverage": "jest --coverage",
4646
"test-integration": "jest --forceExit test/integration",
4747
"test-exports": "cd test/exports && npm run link && npm test",
48-
"test-integration-no-resend": "jest --forceExit --testTimeout=10000 --testPathIgnorePatterns='resend|Resend' --testNamePattern='^((?!(resend|Resend|resent|Resent|gap|Gap)).)*$' test/integration/*.test.js",
49-
"test-integration-resend": "jest --forceExit --testTimeout=15000 --testNamePattern='(resend|Resend|resent|Resent)' test/integration/*.test.js",
48+
"test-integration-no-resend": "jest --forceExit --testTimeout=10000 --testPathIgnorePatterns='resend|Resend' --testNamePattern='^((?!(resend|Resend|resent|Resent|gap|Gap)).)*$' test/integration/*.test.*",
49+
"test-integration-resend": "jest --forceExit --testTimeout=15000 --testNamePattern='(resend|Resend|resent|Resent)' test/integration/*.test.*",
5050
"test-integration-dataunions": "jest --forceExit --testTimeout=15000 --runInBand test/integration/dataunion",
5151
"test-flakey": "jest --forceExit test/flakey/*",
5252
"test-browser": "node ./test/browser/server.js & node node_modules/nightwatch/bin/nightwatch ./test/browser/browser.js && pkill -f server.js",

src/publish/Signer.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,14 @@ const { SigningUtil } = Utils
99
const { SIGNATURE_TYPES } = StreamMessage
1010

1111
type AuthOption = {
12-
ethereum: undefined
12+
ethereum?: never
1313
privateKey: string | Uint8Array
1414
} | {
15-
privateKey: undefined
15+
privateKey?: never
1616
ethereum: EthereumConfig
1717
} | {
18-
ethereum: undefined
19-
privateKey: undefined
18+
ethereum?: never
19+
privateKey?: never
2020
}
2121

2222
function getSigningFunction({

src/stream/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import StorageNode from './StorageNode'
55
import { StreamrClient } from '../StreamrClient'
66

77
// TODO explicit types: e.g. we never provide both streamId and id, or both streamPartition and partition
8-
export type StreamPartDefinition = string | { streamId?: string, streamPartition?: number, id?: string, partition?: number, stream?: Stream }
8+
export type StreamPartDefinition = string | { streamId?: string, streamPartition?: number, id?: string, partition?: number, stream?: Stream|string }
99

1010
export type ValidatedStreamPartDefinition = { streamId: string, streamPartition: number, key: string}
1111

src/subscribe/index.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import MessagePipeline from './pipeline'
1010
import Validator from './Validator'
1111
import messageStream from './messageStream'
1212
import resendStream from './resendStream'
13-
import { Todo } from '../types'
13+
import { MaybeAsync, Todo } from '../types'
1414
import StreamrClient, { StreamPartDefinition, SubscribeOptions } from '..'
1515

1616
/**
@@ -377,7 +377,7 @@ class Subscriptions {
377377
this.subSessions = new Map()
378378
}
379379

380-
async add(opts: StreamPartDefinition, onFinally: Todo = async () => {}) {
380+
async add(opts: StreamPartDefinition, onFinally: MaybeAsync<(err?: any) => void> = async () => {}) {
381381
const options = validateOptions(opts)
382382
const { key } = options
383383

@@ -536,7 +536,7 @@ export class Subscriber {
536536
return this.subscriptions.count(options)
537537
}
538538

539-
async subscribe(opts: StreamPartDefinition, onFinally?: Todo) {
539+
async subscribe(opts: StreamPartDefinition, onFinally?: MaybeAsync<(err?: any) => void>) {
540540
return this.subscriptions.add(opts, onFinally)
541541
}
542542

@@ -571,7 +571,7 @@ export class Subscriber {
571571
return sub
572572
}
573573

574-
async resendSubscribe(opts: SubscribeOptions & StreamPartDefinition, onMessage: Todo) {
574+
async resendSubscribe(opts: SubscribeOptions & StreamPartDefinition, onFinally?: MaybeAsync<(err?: any) => void>) {
575575
// This works by passing a custom message stream to a subscription
576576
// the custom message stream iterates resends, then iterates realtime
577577
const options = validateOptions(opts)
@@ -667,7 +667,7 @@ export class Subscriber {
667667
}
668668
},
669669
],
670-
}, onMessage)
670+
}, onFinally)
671671

672672
// eslint-disable-next-line semi-style
673673
;[resendSubscribeSub] = await Promise.all([

src/user/index.js renamed to src/user/index.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@ import { computeAddress } from '@ethersproject/transactions'
22
import { Web3Provider } from '@ethersproject/providers'
33
import { hexlify } from '@ethersproject/bytes'
44
import { sha256 } from '@ethersproject/sha2'
5+
import { StreamrClient } from '../StreamrClient'
6+
import { EthereumConfig } from '../Config'
57

6-
async function getUsername(client) {
8+
async function getUsername(client: StreamrClient) {
79
const { options: { auth = {} } = {} } = client
810
if (auth.username) { return auth.username }
911

@@ -15,7 +17,7 @@ async function getUsername(client) {
1517
)
1618
}
1719

18-
export async function getAddressFromOptions({ ethereum, privateKey } = {}) {
20+
export async function getAddressFromOptions({ ethereum, privateKey }: { ethereum?: EthereumConfig, privateKey?: any} = {}) {
1921
if (privateKey) {
2022
return computeAddress(privateKey).toLowerCase()
2123
}
@@ -29,7 +31,7 @@ export async function getAddressFromOptions({ ethereum, privateKey } = {}) {
2931
throw new Error('Need either "privateKey" or "ethereum".')
3032
}
3133

32-
export async function getUserId(client) {
34+
export async function getUserId(client: StreamrClient) {
3335
if (client.session.isUnauthenticated()) {
3436
throw new Error('Need to be authenticated to getUserId.')
3537
}

test/integration/GapFill.test.js renamed to test/integration/GapFill.test.ts

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,34 +5,39 @@ import { StreamrClient } from '../../src/StreamrClient'
55
import Connection from '../../src/Connection'
66

77
import config from './config'
8+
import { Stream } from '../../src/stream'
9+
import { Subscriber, Subscription } from '../../src/subscribe'
10+
import { MessageRef } from 'streamr-client-protocol/dist/src/protocol/message_layer'
11+
import { StreamrClientOptions } from '../../src'
812

913
const MAX_MESSAGES = 10
1014

1115
describeRepeats('GapFill with resends', () => {
1216
let expectErrors = 0 // check no errors by default
13-
let publishTestMessages
17+
let publishTestMessages: ReturnType<typeof getPublishTestMessages>
1418
let onError = jest.fn()
15-
let client
16-
let stream
17-
let subscriber
19+
let client: StreamrClient
20+
let stream: Stream
21+
let subscriber: Subscriber
1822

1923
const createClient = (opts = {}) => {
2024
const c = new StreamrClient({
25+
...config.clientOptions,
26+
...opts,
2127
auth: {
2228
privateKey: fakePrivateKey(),
2329
},
2430
autoConnect: false,
2531
autoDisconnect: false,
32+
// @ts-expect-error
2633
maxRetries: 2,
27-
...config.clientOptions,
28-
...opts,
2934
})
3035
c.onError = jest.fn()
3136
c.on('error', onError)
3237
return c
3338
}
3439

35-
async function setupClient(opts) {
40+
async function setupClient(opts: StreamrClientOptions) {
3641
// eslint-disable-next-line require-atomic-updates
3742
client = createClient(opts)
3843
subscriber = client.subscriber
@@ -57,11 +62,11 @@ describeRepeats('GapFill with resends', () => {
5762
if (!subscriber) { return }
5863
expect(subscriber.count(stream.id)).toBe(0)
5964
if (!client) { return }
60-
expect(client.getSubscriptions(stream.id)).toEqual([])
65+
expect(client.getSubscriptions()).toEqual([])
6166
})
6267

6368
afterEach(async () => {
64-
await wait()
69+
await wait(0)
6570
// ensure no unexpected errors
6671
expect(onError).toHaveBeenCalledTimes(expectErrors)
6772
if (client) {
@@ -70,7 +75,7 @@ describeRepeats('GapFill with resends', () => {
7075
})
7176

7277
afterEach(async () => {
73-
await wait()
78+
await wait(0)
7479
if (client) {
7580
client.debug('disconnecting after test >>')
7681
await client.disconnect()
@@ -84,7 +89,7 @@ describeRepeats('GapFill with resends', () => {
8489
}
8590
})
8691

87-
let subs = []
92+
let subs: Subscription[] = []
8893

8994
beforeEach(async () => {
9095
const existingSubs = subs
@@ -108,7 +113,7 @@ describeRepeats('GapFill with resends', () => {
108113
const { parse } = client.connection
109114
let count = 0
110115
client.connection.parse = (...args) => {
111-
const msg = parse.call(client.connection, ...args)
116+
const msg: any = parse.call(client.connection, ...args)
112117
if (!msg.streamMessage) {
113118
return msg
114119
}
@@ -143,7 +148,7 @@ describeRepeats('GapFill with resends', () => {
143148
const { parse } = client.connection
144149
let count = 0
145150
client.connection.parse = (...args) => {
146-
const msg = parse.call(client.connection, ...args)
151+
const msg: any = parse.call(client.connection, ...args)
147152
if (!msg.streamMessage) {
148153
return msg
149154
}
@@ -176,7 +181,7 @@ describeRepeats('GapFill with resends', () => {
176181
const { parse } = client.connection
177182
let count = 0
178183
client.connection.parse = (...args) => {
179-
const msg = parse.call(client.connection, ...args)
184+
const msg: any = parse.call(client.connection, ...args)
180185
if (!msg.streamMessage) {
181186
return msg
182187
}
@@ -208,7 +213,7 @@ describeRepeats('GapFill with resends', () => {
208213
const { parse } = client.connection
209214
let count = 0
210215
client.connection.parse = (...args) => {
211-
const msg = parse.call(client.connection, ...args)
216+
const msg: any = parse.call(client.connection, ...args)
212217
if (!msg.streamMessage) {
213218
return msg
214219
}
@@ -242,9 +247,9 @@ describeRepeats('GapFill with resends', () => {
242247
it('can fill gaps in resends even if gap cannot be filled', async () => {
243248
const { parse } = client.connection
244249
let count = 0
245-
let droppedMsgRef
250+
let droppedMsgRef: MessageRef
246251
client.connection.parse = (...args) => {
247-
const msg = parse.call(client.connection, ...args)
252+
const msg: any = parse.call(client.connection, ...args)
248253
if (!msg.streamMessage) {
249254
return msg
250255
}
@@ -277,7 +282,7 @@ describeRepeats('GapFill with resends', () => {
277282
received.push(m.getParsedContent())
278283
// should not need to explicitly end
279284
}
280-
expect(received).toEqual(published.filter((_value, index) => index !== 2))
285+
expect(received).toEqual(published.filter((_value: any, index: number) => index !== 2))
281286
expect(client.connection.getState()).toBe('connected')
282287
}, 60000)
283288

test/integration/LoginEndpoints.test.js renamed to test/integration/LoginEndpoints.test.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,13 @@ import { StreamrClient } from '../../src/StreamrClient'
77
import config from './config'
88

99
describe('LoginEndpoints', () => {
10-
let client
10+
let client: StreamrClient
1111

1212
const createClient = (opts = {}) => new StreamrClient({
1313
...config.clientOptions,
14-
apiKey: 'tester1-api-key',
14+
auth: {
15+
apiKey: 'tester1-api-key',
16+
},
1517
autoConnect: false,
1618
autoDisconnect: false,
1719
...opts,
@@ -29,8 +31,10 @@ describe('LoginEndpoints', () => {
2931
it('should retrieve a challenge', async () => {
3032
const challenge = await client.getChallenge('some-address')
3133
assert(challenge)
34+
// @ts-expect-error
3235
assert(challenge.id)
3336
assert(challenge.challenge)
37+
// @ts-expect-error
3438
assert(challenge.expires)
3539
})
3640
})
@@ -39,6 +43,7 @@ describe('LoginEndpoints', () => {
3943
it('should fail to get a session token', async () => {
4044
await expect(async () => {
4145
await client.sendChallengeResponse({
46+
// @ts-expect-error
4247
id: 'some-id',
4348
challenge: 'some-challenge',
4449
}, 'some-sig', 'some-address')
@@ -53,6 +58,7 @@ describe('LoginEndpoints', () => {
5358
const sessionToken = await client.sendChallengeResponse(challenge, signature, wallet.address)
5459
assert(sessionToken)
5560
assert(sessionToken.token)
61+
// @ts-expect-error
5662
assert(sessionToken.expires)
5763
})
5864

@@ -61,6 +67,7 @@ describe('LoginEndpoints', () => {
6167
const sessionToken = await client.loginWithChallengeResponse((d) => wallet.signMessage(d), wallet.address)
6268
assert(sessionToken)
6369
assert(sessionToken.token)
70+
// @ts-expect-error
6471
assert(sessionToken.expires)
6572
})
6673
})
@@ -76,6 +83,7 @@ describe('LoginEndpoints', () => {
7683
const sessionToken = await client.loginWithApiKey('tester1-api-key')
7784
assert(sessionToken)
7885
assert(sessionToken.token)
86+
// @ts-expect-error
7987
assert(sessionToken.expires)
8088
})
8189
})

test/integration/ResendReconnect.test.js renamed to test/integration/ResendReconnect.test.ts

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,12 @@ import { StreamrClient } from '../../src/StreamrClient'
55
import { Defer } from '../../src/utils'
66

77
import config from './config'
8+
import { Stream } from '../../src/stream'
9+
import { Subscription } from '../../src'
10+
import { PublishRequest } from 'streamr-client-protocol/dist/src/protocol/control_layer'
811

912
const createClient = (opts = {}) => new StreamrClient({
10-
...(config.clientOptions || {
11-
url: config.websocketUrl,
12-
restUrl: config.restUrl,
13-
}),
13+
...config.clientOptions,
1414
auth: {
1515
privateKey: fakePrivateKey(),
1616
},
@@ -22,10 +22,10 @@ const createClient = (opts = {}) => new StreamrClient({
2222
const MAX_MESSAGES = 3
2323

2424
describe('resend/reconnect', () => {
25-
let client
26-
let stream
27-
let publishedMessages
28-
let publishTestMessages
25+
let client: StreamrClient
26+
let stream: Stream
27+
let publishedMessages: [message: any, request: PublishRequest][]
28+
let publishTestMessages: ReturnType<typeof getPublishTestMessages>
2929

3030
beforeEach(async () => {
3131
client = createClient()
@@ -49,13 +49,13 @@ describe('resend/reconnect', () => {
4949

5050
describe('reconnect with resend', () => {
5151
let shouldDisconnect = false
52-
let sub
53-
let messages = []
52+
let sub: Subscription
53+
let messages: any[] = []
5454
beforeEach(async () => {
5555
const done = Defer()
5656
messages = []
5757
sub = await client.subscribe({
58-
stream: stream.id,
58+
streamId: stream.id,
5959
resend: {
6060
last: MAX_MESSAGES,
6161
},

0 commit comments

Comments
 (0)