diff --git a/package.json b/package.json index 858d8f85d..0a045be7b 100644 --- a/package.json +++ b/package.json @@ -45,8 +45,8 @@ "coverage": "jest --coverage", "test-integration": "jest --forceExit test/integration", "test-exports": "cd test/exports && npm run link && npm test", - "test-integration-no-resend": "jest --forceExit --testTimeout=10000 --testPathIgnorePatterns='resend|Resend' --testNamePattern='^((?!(resend|Resend|resent|Resent|gap|Gap)).)*$' test/integration/*.test.js", - "test-integration-resend": "jest --forceExit --testTimeout=15000 --testNamePattern='(resend|Resend|resent|Resent)' test/integration/*.test.js", + "test-integration-no-resend": "jest --forceExit --testTimeout=10000 --testPathIgnorePatterns='resend|Resend' --testNamePattern='^((?!(resend|Resend|resent|Resent|gap|Gap)).)*$' test/integration/*.test.*", + "test-integration-resend": "jest --forceExit --testTimeout=15000 --testNamePattern='(resend|Resend|resent|Resent)' test/integration/*.test.*", "test-integration-dataunions": "jest --forceExit --testTimeout=15000 --runInBand test/integration/dataunion", "test-flakey": "jest --forceExit test/flakey/*", "test-browser": "node ./test/browser/server.js & node node_modules/nightwatch/bin/nightwatch ./test/browser/browser.js && pkill -f server.js", diff --git a/src/publish/Signer.ts b/src/publish/Signer.ts index 44e5bb875..cec02d2fe 100644 --- a/src/publish/Signer.ts +++ b/src/publish/Signer.ts @@ -9,14 +9,14 @@ const { SigningUtil } = Utils const { SIGNATURE_TYPES } = StreamMessage type AuthOption = { - ethereum: undefined + ethereum?: never privateKey: string | Uint8Array } | { - privateKey: undefined + privateKey?: never ethereum: EthereumConfig } | { - ethereum: undefined - privateKey: undefined + ethereum?: never + privateKey?: never } function getSigningFunction({ diff --git a/src/stream/index.ts b/src/stream/index.ts index 4476be363..4d18e1441 100644 --- a/src/stream/index.ts +++ b/src/stream/index.ts @@ -5,7 +5,7 @@ import StorageNode from './StorageNode' import { StreamrClient } from '../StreamrClient' // TODO explicit types: e.g. we never provide both streamId and id, or both streamPartition and partition -export type StreamPartDefinition = string | { streamId?: string, streamPartition?: number, id?: string, partition?: number, stream?: Stream } +export type StreamPartDefinition = string | { streamId?: string, streamPartition?: number, id?: string, partition?: number, stream?: Stream|string } export type ValidatedStreamPartDefinition = { streamId: string, streamPartition: number, key: string} diff --git a/src/subscribe/index.ts b/src/subscribe/index.ts index 466b2c6ea..e2ae9fc8a 100644 --- a/src/subscribe/index.ts +++ b/src/subscribe/index.ts @@ -10,7 +10,7 @@ import MessagePipeline from './pipeline' import Validator from './Validator' import messageStream from './messageStream' import resendStream from './resendStream' -import { Todo } from '../types' +import { MaybeAsync, Todo } from '../types' import StreamrClient, { StreamPartDefinition, SubscribeOptions } from '..' /** @@ -377,7 +377,7 @@ class Subscriptions { this.subSessions = new Map() } - async add(opts: StreamPartDefinition, onFinally: Todo = async () => {}) { + async add(opts: StreamPartDefinition, onFinally: MaybeAsync<(err?: any) => void> = async () => {}) { const options = validateOptions(opts) const { key } = options @@ -536,7 +536,7 @@ export class Subscriber { return this.subscriptions.count(options) } - async subscribe(opts: StreamPartDefinition, onFinally?: Todo) { + async subscribe(opts: StreamPartDefinition, onFinally?: MaybeAsync<(err?: any) => void>) { return this.subscriptions.add(opts, onFinally) } @@ -571,7 +571,7 @@ export class Subscriber { return sub } - async resendSubscribe(opts: SubscribeOptions & StreamPartDefinition, onMessage: Todo) { + async resendSubscribe(opts: SubscribeOptions & StreamPartDefinition, onFinally?: MaybeAsync<(err?: any) => void>) { // This works by passing a custom message stream to a subscription // the custom message stream iterates resends, then iterates realtime const options = validateOptions(opts) @@ -667,7 +667,7 @@ export class Subscriber { } }, ], - }, onMessage) + }, onFinally) // eslint-disable-next-line semi-style ;[resendSubscribeSub] = await Promise.all([ diff --git a/src/user/index.js b/src/user/index.ts similarity index 85% rename from src/user/index.js rename to src/user/index.ts index 925141ca0..c5c25a626 100644 --- a/src/user/index.js +++ b/src/user/index.ts @@ -2,8 +2,10 @@ import { computeAddress } from '@ethersproject/transactions' import { Web3Provider } from '@ethersproject/providers' import { hexlify } from '@ethersproject/bytes' import { sha256 } from '@ethersproject/sha2' +import { StreamrClient } from '../StreamrClient' +import { EthereumConfig } from '../Config' -async function getUsername(client) { +async function getUsername(client: StreamrClient) { const { options: { auth = {} } = {} } = client if (auth.username) { return auth.username } @@ -15,7 +17,7 @@ async function getUsername(client) { ) } -export async function getAddressFromOptions({ ethereum, privateKey } = {}) { +export async function getAddressFromOptions({ ethereum, privateKey }: { ethereum?: EthereumConfig, privateKey?: any} = {}) { if (privateKey) { return computeAddress(privateKey).toLowerCase() } @@ -29,7 +31,7 @@ export async function getAddressFromOptions({ ethereum, privateKey } = {}) { throw new Error('Need either "privateKey" or "ethereum".') } -export async function getUserId(client) { +export async function getUserId(client: StreamrClient) { if (client.session.isUnauthenticated()) { throw new Error('Need to be authenticated to getUserId.') } diff --git a/test/integration/GapFill.test.js b/test/integration/GapFill.test.ts similarity index 89% rename from test/integration/GapFill.test.js rename to test/integration/GapFill.test.ts index 7eb7dc8fa..cb1b49e15 100644 --- a/test/integration/GapFill.test.js +++ b/test/integration/GapFill.test.ts @@ -5,34 +5,39 @@ import { StreamrClient } from '../../src/StreamrClient' import Connection from '../../src/Connection' import config from './config' +import { Stream } from '../../src/stream' +import { Subscriber, Subscription } from '../../src/subscribe' +import { MessageRef } from 'streamr-client-protocol/dist/src/protocol/message_layer' +import { StreamrClientOptions } from '../../src' const MAX_MESSAGES = 10 describeRepeats('GapFill with resends', () => { let expectErrors = 0 // check no errors by default - let publishTestMessages + let publishTestMessages: ReturnType let onError = jest.fn() - let client - let stream - let subscriber + let client: StreamrClient + let stream: Stream + let subscriber: Subscriber const createClient = (opts = {}) => { const c = new StreamrClient({ + ...config.clientOptions, + ...opts, auth: { privateKey: fakePrivateKey(), }, autoConnect: false, autoDisconnect: false, + // @ts-expect-error maxRetries: 2, - ...config.clientOptions, - ...opts, }) c.onError = jest.fn() c.on('error', onError) return c } - async function setupClient(opts) { + async function setupClient(opts: StreamrClientOptions) { // eslint-disable-next-line require-atomic-updates client = createClient(opts) subscriber = client.subscriber @@ -57,11 +62,11 @@ describeRepeats('GapFill with resends', () => { if (!subscriber) { return } expect(subscriber.count(stream.id)).toBe(0) if (!client) { return } - expect(client.getSubscriptions(stream.id)).toEqual([]) + expect(client.getSubscriptions()).toEqual([]) }) afterEach(async () => { - await wait() + await wait(0) // ensure no unexpected errors expect(onError).toHaveBeenCalledTimes(expectErrors) if (client) { @@ -70,7 +75,7 @@ describeRepeats('GapFill with resends', () => { }) afterEach(async () => { - await wait() + await wait(0) if (client) { client.debug('disconnecting after test >>') await client.disconnect() @@ -84,7 +89,7 @@ describeRepeats('GapFill with resends', () => { } }) - let subs = [] + let subs: Subscription[] = [] beforeEach(async () => { const existingSubs = subs @@ -108,7 +113,7 @@ describeRepeats('GapFill with resends', () => { const { parse } = client.connection let count = 0 client.connection.parse = (...args) => { - const msg = parse.call(client.connection, ...args) + const msg: any = parse.call(client.connection, ...args) if (!msg.streamMessage) { return msg } @@ -143,7 +148,7 @@ describeRepeats('GapFill with resends', () => { const { parse } = client.connection let count = 0 client.connection.parse = (...args) => { - const msg = parse.call(client.connection, ...args) + const msg: any = parse.call(client.connection, ...args) if (!msg.streamMessage) { return msg } @@ -176,7 +181,7 @@ describeRepeats('GapFill with resends', () => { const { parse } = client.connection let count = 0 client.connection.parse = (...args) => { - const msg = parse.call(client.connection, ...args) + const msg: any = parse.call(client.connection, ...args) if (!msg.streamMessage) { return msg } @@ -208,7 +213,7 @@ describeRepeats('GapFill with resends', () => { const { parse } = client.connection let count = 0 client.connection.parse = (...args) => { - const msg = parse.call(client.connection, ...args) + const msg: any = parse.call(client.connection, ...args) if (!msg.streamMessage) { return msg } @@ -242,9 +247,9 @@ describeRepeats('GapFill with resends', () => { it('can fill gaps in resends even if gap cannot be filled', async () => { const { parse } = client.connection let count = 0 - let droppedMsgRef + let droppedMsgRef: MessageRef client.connection.parse = (...args) => { - const msg = parse.call(client.connection, ...args) + const msg: any = parse.call(client.connection, ...args) if (!msg.streamMessage) { return msg } @@ -277,7 +282,7 @@ describeRepeats('GapFill with resends', () => { received.push(m.getParsedContent()) // should not need to explicitly end } - expect(received).toEqual(published.filter((_value, index) => index !== 2)) + expect(received).toEqual(published.filter((_value: any, index: number) => index !== 2)) expect(client.connection.getState()).toBe('connected') }, 60000) diff --git a/test/integration/LoginEndpoints.test.js b/test/integration/LoginEndpoints.test.ts similarity index 92% rename from test/integration/LoginEndpoints.test.js rename to test/integration/LoginEndpoints.test.ts index ce4f94610..748071e27 100644 --- a/test/integration/LoginEndpoints.test.js +++ b/test/integration/LoginEndpoints.test.ts @@ -7,11 +7,13 @@ import { StreamrClient } from '../../src/StreamrClient' import config from './config' describe('LoginEndpoints', () => { - let client + let client: StreamrClient const createClient = (opts = {}) => new StreamrClient({ ...config.clientOptions, - apiKey: 'tester1-api-key', + auth: { + apiKey: 'tester1-api-key', + }, autoConnect: false, autoDisconnect: false, ...opts, @@ -29,8 +31,10 @@ describe('LoginEndpoints', () => { it('should retrieve a challenge', async () => { const challenge = await client.getChallenge('some-address') assert(challenge) + // @ts-expect-error assert(challenge.id) assert(challenge.challenge) + // @ts-expect-error assert(challenge.expires) }) }) @@ -39,6 +43,7 @@ describe('LoginEndpoints', () => { it('should fail to get a session token', async () => { await expect(async () => { await client.sendChallengeResponse({ + // @ts-expect-error id: 'some-id', challenge: 'some-challenge', }, 'some-sig', 'some-address') @@ -53,6 +58,7 @@ describe('LoginEndpoints', () => { const sessionToken = await client.sendChallengeResponse(challenge, signature, wallet.address) assert(sessionToken) assert(sessionToken.token) + // @ts-expect-error assert(sessionToken.expires) }) @@ -61,6 +67,7 @@ describe('LoginEndpoints', () => { const sessionToken = await client.loginWithChallengeResponse((d) => wallet.signMessage(d), wallet.address) assert(sessionToken) assert(sessionToken.token) + // @ts-expect-error assert(sessionToken.expires) }) }) @@ -76,6 +83,7 @@ describe('LoginEndpoints', () => { const sessionToken = await client.loginWithApiKey('tester1-api-key') assert(sessionToken) assert(sessionToken.token) + // @ts-expect-error assert(sessionToken.expires) }) }) diff --git a/test/integration/ResendReconnect.test.js b/test/integration/ResendReconnect.test.ts similarity index 87% rename from test/integration/ResendReconnect.test.js rename to test/integration/ResendReconnect.test.ts index a777acc22..794ee9810 100644 --- a/test/integration/ResendReconnect.test.js +++ b/test/integration/ResendReconnect.test.ts @@ -5,12 +5,12 @@ import { StreamrClient } from '../../src/StreamrClient' import { Defer } from '../../src/utils' import config from './config' +import { Stream } from '../../src/stream' +import { Subscription } from '../../src' +import { PublishRequest } from 'streamr-client-protocol/dist/src/protocol/control_layer' const createClient = (opts = {}) => new StreamrClient({ - ...(config.clientOptions || { - url: config.websocketUrl, - restUrl: config.restUrl, - }), + ...config.clientOptions, auth: { privateKey: fakePrivateKey(), }, @@ -22,10 +22,10 @@ const createClient = (opts = {}) => new StreamrClient({ const MAX_MESSAGES = 3 describe('resend/reconnect', () => { - let client - let stream - let publishedMessages - let publishTestMessages + let client: StreamrClient + let stream: Stream + let publishedMessages: [message: any, request: PublishRequest][] + let publishTestMessages: ReturnType beforeEach(async () => { client = createClient() @@ -49,13 +49,13 @@ describe('resend/reconnect', () => { describe('reconnect with resend', () => { let shouldDisconnect = false - let sub - let messages = [] + let sub: Subscription + let messages: any[] = [] beforeEach(async () => { const done = Defer() messages = [] sub = await client.subscribe({ - stream: stream.id, + streamId: stream.id, resend: { last: MAX_MESSAGES, }, diff --git a/test/integration/Resends.test.js b/test/integration/Resends.test.ts similarity index 90% rename from test/integration/Resends.test.js rename to test/integration/Resends.test.ts index 836632117..6161074e2 100644 --- a/test/integration/Resends.test.js +++ b/test/integration/Resends.test.ts @@ -6,6 +6,7 @@ import { Defer, pTimeout } from '../../src/utils' import Connection from '../../src/Connection' import config from './config' +import { Stream } from '../../src/stream' const MAX_MESSAGES = 10 const WAIT_FOR_STORAGE_TIMEOUT = 6000 @@ -25,6 +26,7 @@ describe('StreamrClient resends', () => { }, autoConnect: false, autoDisconnect: false, + // @ts-expect-error maxRetries: 2, ...opts, }) @@ -33,10 +35,10 @@ describe('StreamrClient resends', () => { return c } - let client - let stream - let published - let publishTestMessages + let client: StreamrClient + let stream: Stream + let published: any[] + let publishTestMessages: ReturnType beforeEach(async () => { client = createClient() @@ -46,7 +48,7 @@ describe('StreamrClient resends', () => { }) afterEach(async () => { - await wait() + await wait(0) // ensure no unexpected errors expect(onError).toHaveBeenCalledTimes(expectErrors) if (client) { @@ -86,8 +88,8 @@ describe('StreamrClient resends', () => { describe('issue resend and subscribe at the same time', () => { it('works with resend -> subscribe', async () => { - const resentMessages = [] - const realtimeMessages = [] + const resentMessages: any[] = [] + const realtimeMessages: any[] = [] const realtimeMessage = { msg: uid('realtimeMessage'), @@ -103,7 +105,7 @@ describe('StreamrClient resends', () => { }) await client.subscribe({ - stream: stream.id, + streamId: stream.id, }, (message) => { realtimeMessages.push(message) }) @@ -118,15 +120,15 @@ describe('StreamrClient resends', () => { }, 18000) it('works with subscribe -> resend', async () => { - const resentMessages = [] - const realtimeMessages = [] + const resentMessages: any[] = [] + const realtimeMessages: any[] = [] const realtimeMessage = { msg: uid('realtimeMessage'), } await client.subscribe({ - stream: stream.id, + streamId: stream.id, }, (message) => { realtimeMessages.push(message) }) @@ -151,15 +153,15 @@ describe('StreamrClient resends', () => { }, 15000) it('works with subscribe+resend -> subscribe', async () => { - const resentMessages = [] - const realtimeMessages = [] + const resentMessages: any[] = [] + const realtimeMessages: any[] = [] const realtimeMessage = { msg: uid('realtimeMessage'), } client.subscribe({ - stream: stream.id, + streamId: stream.id, resend: { last: MAX_MESSAGES, }, @@ -168,7 +170,7 @@ describe('StreamrClient resends', () => { }) client.subscribe({ - stream: stream.id, + streamId: stream.id, }, (message) => { realtimeMessages.push(message) }) @@ -183,22 +185,22 @@ describe('StreamrClient resends', () => { }, 15000) it('works with subscribe -> subscribe+resend', async () => { - const resentMessages = [] - const realtimeMessages = [] + const resentMessages: any[] = [] + const realtimeMessages: any[] = [] const realtimeMessage = { msg: uid('realtimeMessage'), } client.subscribe({ - stream: stream.id, + streamId: stream.id, }, (message) => { realtimeMessages.push(message) }) // subscribe with resend after realtime subscribe client.subscribe({ - stream: stream.id, + streamId: stream.id, resend: { last: MAX_MESSAGES, }, @@ -219,7 +221,7 @@ describe('StreamrClient resends', () => { describeRepeats('resend repeats', () => { // eslint-disable-next-line no-loop-func test('resend last using resend function', async () => { - const receivedMessages = [] + const receivedMessages: any[] = [] // eslint-disable-next-line no-await-in-loop const sub = await client.resend( @@ -245,11 +247,11 @@ describe('StreamrClient resends', () => { // eslint-disable-next-line no-loop-func test('resend last using subscribe function', async () => { - const receivedMessages = [] + const receivedMessages: any[] = [] // eslint-disable-next-line no-await-in-loop const sub = await client.subscribe({ - stream: stream.id, + streamId: stream.id, resend: { last: MAX_MESSAGES, }, @@ -263,10 +265,10 @@ describe('StreamrClient resends', () => { }) it('resend last using subscribe and publish messages after resend', async () => { - const receivedMessages = [] + const receivedMessages: any[] = [] await client.subscribe({ - stream: stream.id, + streamId: stream.id, resend: { last: MAX_MESSAGES, }, @@ -294,10 +296,10 @@ describe('StreamrClient resends', () => { }, 40000) it('resend last using subscribe and publish realtime messages', async () => { - const receivedMessages = [] + const receivedMessages: any[] = [] const sub = await client.subscribe({ - stream: stream.id, + streamId: stream.id, resend: { last: MAX_MESSAGES, }, @@ -349,7 +351,7 @@ describe('StreamrClient resends', () => { // resend from LONG_RESEND messages await client.connect() - const receivedMessages = [] + const receivedMessages: any[] = [] const onGotFirstMessage = Defer() const sub = await client.resend({ stream: stream.id, @@ -361,7 +363,7 @@ describe('StreamrClient resends', () => { }, (msg) => { receivedMessages.push(msg) if (receivedMessages.length === 1) { - onGotFirstMessage.resolve() + onGotFirstMessage.resolve(undefined) } }) @@ -374,6 +376,7 @@ describe('StreamrClient resends', () => { expect(receivedMessages).toEqual(published) expect(published.length).toBe(LONG_RESEND) }, 300000) + // @ts-expect-error }, 300000) }) }) diff --git a/test/integration/Sequencing.test.js b/test/integration/Sequencing.test.ts similarity index 91% rename from test/integration/Sequencing.test.js rename to test/integration/Sequencing.test.ts index f9ee621bd..efaf0e54c 100644 --- a/test/integration/Sequencing.test.js +++ b/test/integration/Sequencing.test.ts @@ -5,14 +5,15 @@ import { StreamrClient } from '../../src/StreamrClient' import Connection from '../../src/Connection' import config from './config' +import { Stream } from '../../src/stream' -const Msg = (opts) => ({ +const Msg = (opts?: any) => ({ value: uid('msg'), ...opts, }) -function toSeq(requests, ts = Date.now()) { - return requests.map((m) => { +function toSeq(requests: any[], ts = Date.now()) { + return requests.map((m: any) => { const { prevMsgRef } = m.streamMessage return [ [m.streamMessage.getTimestamp() - ts, m.streamMessage.getSequenceNumber()], @@ -24,8 +25,8 @@ function toSeq(requests, ts = Date.now()) { describe('Sequencing', () => { let expectErrors = 0 // check no errors by default let onError = jest.fn() - let client - let stream + let client: StreamrClient + let stream: Stream const createClient = (opts = {}) => { const c = new StreamrClient({ @@ -35,6 +36,7 @@ describe('Sequencing', () => { }, autoConnect: false, autoDisconnect: false, + // @ts-expect-error maxRetries: 2, ...opts, }) @@ -55,7 +57,7 @@ describe('Sequencing', () => { }) afterEach(async () => { - await wait() + await wait(0) // ensure no unexpected errors expect(onError).toHaveBeenCalledTimes(expectErrors) if (client) { @@ -64,7 +66,7 @@ describe('Sequencing', () => { }) afterEach(async () => { - await wait() + await wait(0) if (client) { client.debug('disconnecting after test') await client.disconnect() @@ -79,8 +81,8 @@ describe('Sequencing', () => { it('should sequence in order', async () => { const ts = Date.now() - const msgsPublished = [] - const msgsReceieved = [] + const msgsPublished: any[] = [] + const msgsReceieved: any[] = [] await client.subscribe(stream.id, (m) => msgsReceieved.push(m)) @@ -115,8 +117,8 @@ describe('Sequencing', () => { it('should sequence in order even if some calls delayed', async () => { const ts = Date.now() - const msgsPublished = [] - const msgsReceieved = [] + const msgsPublished: any[] = [] + const msgsReceieved: any[] = [] let calls = 0 const getStream = client.getStream.bind(client) @@ -164,12 +166,12 @@ describe('Sequencing', () => { it.skip('should sequence in order even if publish requests backdated', async () => { const ts = Date.now() - const msgsPublished = [] - const msgsReceieved = [] + const msgsPublished: any[] = [] + const msgsReceieved: any[] = [] await client.subscribe(stream.id, (m) => msgsReceieved.push(m)) - const nextMsg = (...args) => { + const nextMsg = (...args: any[]) => { const msg = Msg(...args) msgsPublished.push(msg) return msg @@ -200,7 +202,7 @@ describe('Sequencing', () => { timeout: 6000, }) await waitForStorage(lastRequest) - const msgsResent = [] + const msgsResent: any[] = [] const sub = await client.resend({ stream: stream.id, resend: { @@ -229,12 +231,12 @@ describe('Sequencing', () => { it.skip('should sequence in order even if publish requests backdated in sequence', async () => { const ts = Date.now() - const msgsPublished = [] - const msgsReceieved = [] + const msgsPublished: any[] = [] + const msgsReceieved: any[] = [] await client.subscribe(stream.id, (m) => msgsReceieved.push(m)) - const nextMsg = (...args) => { + const nextMsg = (...args: any[]) => { const msg = Msg(...args) msgsPublished.push(msg) return msg @@ -270,7 +272,7 @@ describe('Sequencing', () => { }) await waitForStorage(lastRequest) - const msgsResent = [] + const msgsResent: any[] = [] const sub = await client.resend({ stream: stream.id, resend: { diff --git a/test/integration/Session.test.js b/test/integration/Session.test.ts similarity index 100% rename from test/integration/Session.test.js rename to test/integration/Session.test.ts index bccd20182..960bb4ccc 100644 --- a/test/integration/Session.test.js +++ b/test/integration/Session.test.ts @@ -5,10 +5,10 @@ import config from './config' describe('Session', () => { const createClient = (opts = {}) => new StreamrClient({ - autoConnect: false, - autoDisconnect: false, ...config.clientOptions, ...opts, + autoConnect: false, + autoDisconnect: false, }) describe('Token retrievals', () => { diff --git a/test/integration/Stream.test.js b/test/integration/Stream.test.ts similarity index 97% rename from test/integration/Stream.test.js rename to test/integration/Stream.test.ts index 19df708a3..b3bc0de6f 100644 --- a/test/integration/Stream.test.js +++ b/test/integration/Stream.test.ts @@ -1,4 +1,5 @@ import { StreamrClient } from '../../src/StreamrClient' +import { Stream } from '../../src/stream' import { uid, fakePrivateKey, getPublishTestMessages } from '../utils' import config from './config' @@ -14,8 +15,8 @@ const createClient = (opts = {}) => new StreamrClient({ }) describe('Stream', () => { - let client - let stream + let client: StreamrClient + let stream: Stream beforeEach(async () => { client = createClient() diff --git a/test/integration/StreamConnectionState.test.js b/test/integration/StreamConnectionState.test.ts similarity index 90% rename from test/integration/StreamConnectionState.test.js rename to test/integration/StreamConnectionState.test.ts index d8fcd8c4e..8cc88cbb8 100644 --- a/test/integration/StreamConnectionState.test.js +++ b/test/integration/StreamConnectionState.test.ts @@ -7,17 +7,20 @@ import { Defer, pLimitFn } from '../../src/utils' import Connection from '../../src/Connection' import config from './config' +import { Stream } from '../../src/stream' +import { Subscriber, Subscription } from '../../src/subscribe' +import { StreamrClientOptions } from '../../src' const { ControlMessage } = ControlLayer const MAX_MESSAGES = 5 describeRepeats('Connection State', () => { let expectErrors = 0 // check no errors by default - let publishTestMessages + let publishTestMessages: ReturnType let onError = jest.fn() - let client - let stream - let subscriber + let client: StreamrClient + let stream: Stream + let subscriber: Subscriber const createClient = (opts = {}) => { const c = new StreamrClient({ @@ -27,6 +30,7 @@ describeRepeats('Connection State', () => { }, autoConnect: false, autoDisconnect: false, + // @ts-expect-error publishAutoDisconnectDelay: 250, maxRetries: 2, ...opts, @@ -36,7 +40,7 @@ describeRepeats('Connection State', () => { return c } - async function setupClient(opts) { + async function setupClient(opts: StreamrClientOptions) { // eslint-disable-next-line require-atomic-updates client = createClient(opts) subscriber = client.subscriber @@ -61,11 +65,11 @@ describeRepeats('Connection State', () => { if (!subscriber) { return } expect(subscriber.count(stream.id)).toBe(0) if (!client) { return } - expect(client.getSubscriptions(stream.id)).toEqual([]) + expect(client.getSubscriptions()).toEqual([]) }) afterEach(async () => { - await wait() + await wait(0) // ensure no unexpected errors expect(onError).toHaveBeenCalledTimes(expectErrors) if (client) { @@ -74,7 +78,7 @@ describeRepeats('Connection State', () => { }) afterEach(async () => { - await wait() + await wait(0) if (client) { client.debug('disconnecting after test >>') await client.disconnect() @@ -88,7 +92,7 @@ describeRepeats('Connection State', () => { } }) - let subs = [] + let subs: Subscription[] = [] beforeEach(async () => { const existingSubs = subs @@ -182,7 +186,7 @@ describeRepeats('Connection State', () => { const done = Defer() - const msgs = [] + const msgs: any[] = [] const sockets = new Set() await otherClient.subscribe({ stream, @@ -193,7 +197,7 @@ describeRepeats('Connection State', () => { msgs.push(msg) if (msgs.length === MAX_MESSAGES) { // should eventually get here - done.resolve() + done.resolve(undefined) } // disconnect after every message @@ -242,7 +246,7 @@ describeRepeats('Connection State', () => { await subscriber.subscribe(stream.id) }).rejects.toThrow() expect(subscriber.count(stream.id)).toBe(0) - expect(client.getSubscriptions(stream.id)).toEqual([]) + expect(client.getSubscriptions()).toEqual([]) }) it('should reconnect subscriptions when connection disconnected before subscribed & reconnected', async () => { @@ -251,7 +255,7 @@ describeRepeats('Connection State', () => { client.connection.socket.close() const published = await publishTestMessages(2) const sub = await subTask - expect(client.getSubscriptions(stream.id)).toHaveLength(1) + expect(client.getSubscriptions()).toHaveLength(1) subs.push(sub) const received = [] for await (const msg of sub) { @@ -262,7 +266,7 @@ describeRepeats('Connection State', () => { break } expect(subscriber.count(stream.id)).toBe(0) - expect(client.getSubscriptions(stream.id)).toEqual([]) + expect(client.getSubscriptions()).toEqual([]) }) it('should re-subscribe when subscribed then reconnected + fill gaps', async () => { @@ -285,7 +289,7 @@ describeRepeats('Connection State', () => { } } expect(subscriber.count(stream.id)).toBe(0) - expect(client.getSubscriptions(stream.id)).toEqual([]) + expect(client.getSubscriptions()).toEqual([]) }, 30000) it('should end when subscribed then disconnected', async () => { @@ -303,19 +307,19 @@ describeRepeats('Connection State', () => { } expect(received).toEqual(published.slice(0, 1)) expect(subscriber.count(stream.id)).toBe(0) - expect(client.getSubscriptions(stream.id)).toEqual([]) + expect(client.getSubscriptions()).toEqual([]) }) it('should end when subscribed then disconnected then connected', async () => { const sub = await subscriber.subscribe(stream.id) - expect(client.getSubscriptions(stream.id)).toHaveLength(1) + expect(client.getSubscriptions()).toHaveLength(1) subs.push(sub) await publishTestMessages(2) const received = [] await client.disconnect() expect(subscriber.count(stream.id)).toBe(0) - expect(client.getSubscriptions(stream.id)).toHaveLength(0) + expect(client.getSubscriptions()).toHaveLength(0) for await (const msg of sub) { received.push(msg.getParsedContent()) } @@ -327,7 +331,7 @@ describeRepeats('Connection State', () => { const published2 = await publishTestMessages(2) const received2 = [] expect(subscriber.count(stream.id)).toBe(1) - expect(client.getSubscriptions(stream.id)).toHaveLength(1) + expect(client.getSubscriptions()).toHaveLength(1) for await (const msg of sub2) { received2.push(msg.getParsedContent()) if (received2.length === 1) { @@ -336,7 +340,7 @@ describeRepeats('Connection State', () => { } expect(received2).toEqual(published2.slice(0, 1)) expect(subscriber.count(stream.id)).toBe(0) - expect(client.getSubscriptions(stream.id)).toEqual([]) + expect(client.getSubscriptions()).toEqual([]) }) it('should just end subs when disconnected', async () => { @@ -348,7 +352,7 @@ describeRepeats('Connection State', () => { }) describe('resubscribe on unexpected disconnection', () => { - let otherClient + let otherClient: StreamrClient beforeEach(async () => { otherClient = createClient({ @@ -360,7 +364,8 @@ describeRepeats('Connection State', () => { otherClient.connect(), otherClient.session.getSessionToken(), ] - await Promise.allSettled(tasks) + await (Promise as any).allSettled(tasks) + // @ts-expect-error await Promise.all(tasks) // throw if there were an error }) @@ -369,21 +374,21 @@ describeRepeats('Connection State', () => { otherClient.disconnect(), client.disconnect(), ] - await Promise.allSettled(tasks) + await (Promise as any).allSettled(tasks) await Promise.all(tasks) // throw if there were an error }) it('should work', async () => { const done = Defer() - const msgs = [] + const msgs: any[] = [] await otherClient.subscribe(stream, (msg) => { msgs.push(msg) if (msgs.length === MAX_MESSAGES) { // should eventually get here - done.resolve() + done.resolve(undefined) } }) @@ -399,7 +404,9 @@ describeRepeats('Connection State', () => { disconnect() }) + // @ts-expect-error otherClient.connection.on(ControlMessage.TYPES.BroadcastMessage, onConnectionMessage) + // @ts-expect-error otherClient.connection.on(ControlMessage.TYPES.UnicastMessage, onConnectionMessage) const onConnected = jest.fn() diff --git a/test/integration/StreamrClient.test.js b/test/integration/StreamrClient.test.ts similarity index 91% rename from test/integration/StreamrClient.test.js rename to test/integration/StreamrClient.test.ts index 3f22997b8..2d2de81e6 100644 --- a/test/integration/StreamrClient.test.js +++ b/test/integration/StreamrClient.test.ts @@ -11,6 +11,8 @@ import { Defer, pLimitFn } from '../../src/utils' import Connection from '../../src/Connection' import config from './config' +import { Stream } from '../../src/stream' +import { Subscription } from '../../src' const WebSocket = require('ws') @@ -21,14 +23,14 @@ const MAX_MESSAGES = 20 describeRepeats('StreamrClient', () => { let expectErrors = 0 // check no errors by default - let errors = [] + let errors: any[] = [] - const getOnError = (errs) => jest.fn((err) => { + const getOnError = (errs: any) => jest.fn((err) => { errs.push(err) }) let onError = jest.fn() - let client + let client: StreamrClient const createClient = (opts = {}) => { const c = new StreamrClient({ @@ -40,6 +42,7 @@ describeRepeats('StreamrClient', () => { autoDisconnect: false, // disconnectDelay: 500, // publishAutoDisconnectDelay: 250, + // @ts-expect-error maxRetries: 2, ...opts, }) @@ -65,10 +68,10 @@ describeRepeats('StreamrClient', () => { const ws = new WebSocket(c.options.url) ws.once('open', () => { c.debug('open', c.options.url) - resolve() + resolve(undefined) ws.close() }) - ws.once('error', (err) => { + ws.once('error', (err: any) => { c.debug('err', c.options.url, err) reject(err) ws.terminate() @@ -101,7 +104,7 @@ describeRepeats('StreamrClient', () => { }) afterEach(async () => { - await wait() + await wait(0) // ensure no unexpected errors expect(errors).toHaveLength(expectErrors) if (client) { @@ -110,7 +113,7 @@ describeRepeats('StreamrClient', () => { }) afterEach(async () => { - await wait() + await wait(0) if (client) { client.debug('disconnecting after test') await client.disconnect() @@ -307,7 +310,7 @@ describeRepeats('StreamrClient', () => { client.once('disconnected', done.wrapError(async () => { client.once('connected', done.wrapError(async () => { await client.disconnect() - done.resolve() + done.resolve(undefined) })) await expect(async () => { @@ -407,7 +410,7 @@ describeRepeats('StreamrClient', () => { it('should not subscribe to unsubscribed streams on reconnect', async () => { client = createClient() await client.connect() - const sessionToken = await client.session.getSessionToken() + const sessionToken = await client.session.getSessionToken()! const stream = await client.createStream({ name: uid('stream') @@ -427,14 +430,15 @@ describeRepeats('StreamrClient', () => { expect(connectionEventSpy.mock.calls[0]).toEqual([new SubscribeRequest({ streamId: stream.id, streamPartition: 0, - sessionToken, + sessionToken: sessionToken!, requestId: connectionEventSpy.mock.calls[0][0].requestId, })]) expect(connectionEventSpy.mock.calls[1]).toEqual([new UnsubscribeRequest({ streamId: stream.id, streamPartition: 0, - sessionToken, + // @ts-expect-error + sessionToken: sessionToken!, requestId: connectionEventSpy.mock.calls[1][0].requestId, })]) }) @@ -442,7 +446,7 @@ describeRepeats('StreamrClient', () => { it('should not subscribe after resend() on reconnect', async () => { client = createClient() await client.connect() - const sessionToken = await client.session.getSessionToken() + const sessionToken = await client.session.getSessionToken()! const stream = await client.createStream({ name: uid('stream') @@ -466,7 +470,7 @@ describeRepeats('StreamrClient', () => { expect(connectionEventSpy.mock.calls[0]).toEqual([new ResendLastRequest({ streamId: stream.id, streamPartition: 0, - sessionToken, + sessionToken: sessionToken!, numberLast: 10, requestId: connectionEventSpy.mock.calls[0][0].requestId, })]) @@ -542,7 +546,7 @@ describeRepeats('StreamrClient', () => { id1: uid('msg') } const p = client.publish(stream.id, message) - await wait() + await wait(0) await client.disconnect() // start async disconnect after publish started await expect(p).rejects.toThrow() expect(client.isDisconnected()).toBeTruthy() @@ -565,7 +569,7 @@ describeRepeats('StreamrClient', () => { id1: uid('msg') } const p = client.publish(stream.id, message) - await wait() + await wait(0) await client.disconnect() // start async disconnect after publish started await expect(p).rejects.toThrow() expect(client.isDisconnected()).toBeTruthy() @@ -587,7 +591,7 @@ describeRepeats('StreamrClient', () => { }) await client.subscribe({ - stream: stream.id, + streamId: stream.id, }, () => {}) await client.disconnect() @@ -605,7 +609,7 @@ describeRepeats('StreamrClient', () => { }) await client.subscribe({ - stream: stream.id, + streamId: stream.id, resend: { from: { timestamp: 0, @@ -620,14 +624,14 @@ describeRepeats('StreamrClient', () => { }) describe('StreamrClient', () => { - let stream - let waitForStorage - let publishTestMessages + let stream: Stream + let waitForStorage: (...args: any[]) => Promise + let publishTestMessages: ReturnType // These tests will take time, especially on Travis const TIMEOUT = 30 * 1000 - const attachSubListeners = (sub) => { + const attachSubListeners = (sub: Subscription) => { const onSubscribed = jest.fn() sub.on('subscribed', onSubscribed) const onResent = jest.fn() @@ -672,13 +676,13 @@ describeRepeats('StreamrClient', () => { }) afterEach(async () => { - await wait() + await wait(0) // ensure no unexpected errors expect(onError).toHaveBeenCalledTimes(expectErrors) }) afterEach(async () => { - await wait() + await wait(0) if (client) { client.debug('disconnecting after test') @@ -722,36 +726,37 @@ describeRepeats('StreamrClient', () => { describe('subscribe/unsubscribe', () => { beforeEach(() => { - expect(client.getSubscriptions(stream.id)).toHaveLength(0) + expect(client.getSubscriptions()).toHaveLength(0) }) it('client.subscribe then unsubscribe after subscribed', async () => { const sub = await client.subscribe({ - stream: stream.id, + streamId: stream.id, }, () => {}) const events = attachSubListeners(sub) - expect(client.getSubscriptions(stream.id)).toHaveLength(1) // has subscription immediately - expect(client.getSubscriptions(stream.id)).toHaveLength(1) + expect(client.getSubscriptions()).toHaveLength(1) // has subscription immediately + expect(client.getSubscriptions()).toHaveLength(1) await client.unsubscribe(sub) - expect(client.getSubscriptions(stream.id)).toHaveLength(0) + expect(client.getSubscriptions()).toHaveLength(0) expect(events.onUnsubscribed).toHaveBeenCalledTimes(1) }, TIMEOUT) it('client.subscribe then unsubscribe before subscribed', async () => { client.connection.enableAutoDisconnect(false) const subTask = client.subscribe({ - stream: stream.id, + streamId: stream.id, }, () => {}) const events = attachSubListeners(client.subscriber.getSubscriptionSession(stream)) - expect(client.getSubscriptions(stream.id)).toHaveLength(1) + expect(client.getSubscriptions()).toHaveLength(1) + // @ts-expect-error const unsubTask = client.unsubscribe(stream) - expect(client.getSubscriptions(stream.id)).toHaveLength(0) // lost subscription immediately + expect(client.getSubscriptions()).toHaveLength(0) // lost subscription immediately await unsubTask await subTask await wait(TIMEOUT * 0.2) @@ -763,13 +768,14 @@ describeRepeats('StreamrClient', () => { it('client.subscribe then unsubscribe before subscribed after started subscribing', async () => { client.connection.enableAutoDisconnect(false) const subTask = client.subscribe({ - stream: stream.id, + streamId: stream.id, }, () => {}) const subSession = client.subscriber.getSubscriptionSession(stream) const events = attachSubListeners(subSession) let unsubTask const startedSubscribing = Defer() subSession.once('subscribing', startedSubscribing.wrap(() => { + // @ts-expect-error unsubTask = client.unsubscribe(stream) })) @@ -778,7 +784,7 @@ describeRepeats('StreamrClient', () => { unsubTask, subTask, ]) - expect(client.getSubscriptions(stream.id)).toHaveLength(0) // lost subscription immediately + expect(client.getSubscriptions()).toHaveLength(0) // lost subscription immediately await wait(TIMEOUT * 0.2) expect(events.onResent).toHaveBeenCalledTimes(0) expect(events.onSubscribed).toHaveBeenCalledTimes(0) @@ -789,7 +795,7 @@ describeRepeats('StreamrClient', () => { it('client.subscribe then unsubscribe before subscribed', async () => { client.connection.enableAutoDisconnect(false) const subTask = client.subscribe({ - stream: stream.id, + streamId: stream.id, resend: { from: { timestamp: 0, @@ -799,11 +805,12 @@ describeRepeats('StreamrClient', () => { const events = attachSubListeners(client.subscriber.getSubscriptionSession(stream)) - expect(client.getSubscriptions(stream.id)).toHaveLength(1) + expect(client.getSubscriptions()).toHaveLength(1) + // @ts-expect-error const unsubTask = client.unsubscribe(stream) - expect(client.getSubscriptions(stream.id)).toHaveLength(0) // lost subscription immediately + expect(client.getSubscriptions()).toHaveLength(0) // lost subscription immediately await unsubTask await subTask await wait(TIMEOUT * 0.2) @@ -815,7 +822,7 @@ describeRepeats('StreamrClient', () => { it('client.subscribe then unsubscribe ignores messages with resend', async () => { const onMessage = jest.fn() const subTask = client.subscribe({ - stream: stream.id, + streamId: stream.id, resend: { from: { timestamp: 0, @@ -824,8 +831,9 @@ describeRepeats('StreamrClient', () => { }, onMessage) const events = attachSubListeners(client.subscriber.getSubscriptionSession(stream)) + // @ts-expect-error const unsubTask = client.unsubscribe(stream) - expect(client.getSubscriptions(stream.id)).toHaveLength(0) // lost subscription immediately + expect(client.getSubscriptions()).toHaveLength(0) // lost subscription immediately const msg = Msg() const publishReq = await stream.publish(msg) @@ -844,15 +852,15 @@ describeRepeats('StreamrClient', () => { it('client.subscribe then unsubscribe ignores messages', async () => { const onMessage = jest.fn() const sub = await client.subscribe({ - stream: stream.id, + streamId: stream.id, }, onMessage) - expect(client.getSubscriptions(stream.id)).toHaveLength(1) + expect(client.getSubscriptions()).toHaveLength(1) const events = attachSubListeners(sub) const t = client.unsubscribe(sub) await stream.publish(Msg()) await t - expect(client.getSubscriptions(stream.id)).toHaveLength(0) // lost subscription immediately + expect(client.getSubscriptions()).toHaveLength(0) // lost subscription immediately await wait(TIMEOUT * 0.2) expect(events.onResent).toHaveBeenCalledTimes(0) expect(events.onSubscribed).toHaveBeenCalledTimes(0) @@ -864,7 +872,7 @@ describeRepeats('StreamrClient', () => { const id = Date.now() const done = Defer() const sub = await client.subscribe({ - stream: stream.id, + streamId: stream.id, }, done.wrap(async (parsedContent, streamMessage) => { expect(parsedContent.id).toBe(id) @@ -884,9 +892,9 @@ describeRepeats('StreamrClient', () => { }) it('client.subscribe with onMessage & collect', async () => { - const onMessageMsgs = [] + const onMessageMsgs: any[] = [] const sub = await client.subscribe({ - stream: stream.id, + streamId: stream.id, }, async (msg) => { onMessageMsgs.push(msg) }) @@ -897,19 +905,19 @@ describeRepeats('StreamrClient', () => { }) describe('resubscribe on unexpected disconnection', () => { - let otherClient + let otherClient: StreamrClient beforeEach(async () => { otherClient = createClient({ auth: client.options.auth, }) - const tasks = [ + const tasks: Promise[] = [ client.connect(), client.session.getSessionToken(), otherClient.connect(), otherClient.session.getSessionToken(), ] - await Promise.allSettled(tasks) + await (Promise as any).allSettled(tasks) await Promise.all(tasks) // throw if there were an error }) @@ -919,13 +927,13 @@ describeRepeats('StreamrClient', () => { otherClient.disconnect(), client.disconnect(), ] - await Promise.allSettled(tasks) + await (Promise as any).allSettled(tasks) await Promise.all(tasks) // throw if there were an error }) it('should work', async () => { const done = Defer() - const msgs = [] + const msgs: any[] = [] await otherClient.subscribe(stream, (msg) => { msgs.push(msg) @@ -933,7 +941,7 @@ describeRepeats('StreamrClient', () => { otherClient.debug('got msg %d of %d', msgs.length, MAX_MESSAGES) if (msgs.length === MAX_MESSAGES) { // should eventually get here - done.resolve() + done.resolve(undefined) } }) @@ -951,7 +959,9 @@ describeRepeats('StreamrClient', () => { disconnect() }) + // @ts-expect-error otherClient.connection.on(ControlMessage.TYPES.BroadcastMessage, onConnectionMessage) + // @ts-expect-error otherClient.connection.on(ControlMessage.TYPES.UnicastMessage, onConnectionMessage) const onConnected = jest.fn() @@ -977,9 +987,9 @@ describeRepeats('StreamrClient', () => { it('publish and subscribe a sequence of messages', async () => { client.enableAutoConnect() const done = Defer() - const received = [] + const received: any[] = [] const sub = await client.subscribe({ - stream: stream.id, + streamId: stream.id, }, done.wrapError((parsedContent, streamMessage) => { received.push(parsedContent) // Check signature stuff @@ -1007,6 +1017,7 @@ describeRepeats('StreamrClient', () => { client.on('disconnected', onDisconnected) client.on('connected', onConnected) + // @ts-expect-error client.options.publishAutoDisconnectDelay = 1000 // eslint-disable-line require-atomic-updates client.enableAutoConnect() @@ -1015,6 +1026,7 @@ describeRepeats('StreamrClient', () => { delay: 150, }) + // @ts-expect-error await wait(client.options.publishAutoDisconnectDelay * 1.5) expect(onConnected).toHaveBeenCalledTimes(1) @@ -1027,10 +1039,10 @@ describeRepeats('StreamrClient', () => { waitForLast: true, }) - const received = [] + const received: any[] = [] const sub = await client.subscribe({ - stream: stream.id, + streamId: stream.id, resend: { from: { timestamp: 0, @@ -1044,7 +1056,7 @@ describeRepeats('StreamrClient', () => { expect(streamMessage.getPublisherId()).toBeTruthy() expect(streamMessage.signature).toBeTruthy() if (received.length === published.length) { - done.resolve() + done.resolve(undefined) } })) @@ -1052,7 +1064,7 @@ describeRepeats('StreamrClient', () => { expect(received).toEqual(published) // All good, unsubscribe await client.unsubscribe(sub) - expect(client.getSubscriptions(stream.id)).toHaveLength(0) + expect(client.getSubscriptions()).toHaveLength(0) }, TIMEOUT) it('client.subscribe with resend last', async () => { @@ -1061,10 +1073,10 @@ describeRepeats('StreamrClient', () => { waitForLast: true, }) - const received = [] + const received: any[] = [] const sub = await client.subscribe({ - stream: stream.id, + streamId: stream.id, resend: { last: 2 }, @@ -1075,7 +1087,7 @@ describeRepeats('StreamrClient', () => { expect(streamMessage.getPublisherId()).toBeTruthy() expect(streamMessage.signature).toBeTruthy() if (received.length === 2) { - done.resolve() + done.resolve(undefined) } })) @@ -1083,7 +1095,7 @@ describeRepeats('StreamrClient', () => { // All good, unsubscribe await client.unsubscribe(sub) expect(received).toEqual(published.slice(-2)) - expect(client.getSubscriptions(stream.id)).toHaveLength(0) + expect(client.getSubscriptions()).toHaveLength(0) }, TIMEOUT) it('client.subscribe (realtime with resend)', async () => { @@ -1092,10 +1104,10 @@ describeRepeats('StreamrClient', () => { waitForLast: true, }) - const received = [] + const received: any[] = [] const sub = await client.subscribe({ - stream: stream.id, + streamId: stream.id, resend: { last: 2 }, @@ -1106,7 +1118,7 @@ describeRepeats('StreamrClient', () => { expect(streamMessage.getPublisherId()).toBeTruthy() expect(streamMessage.signature).toBeTruthy() if (received.length === 3) { - done.resolve() + done.resolve(undefined) } })) @@ -1116,13 +1128,13 @@ describeRepeats('StreamrClient', () => { // All good, unsubscribe await client.unsubscribe(sub) expect(received).toEqual([...published.slice(-2), msg]) - expect(client.getSubscriptions(stream.id)).toHaveLength(0) + expect(client.getSubscriptions()).toHaveLength(0) }, TIMEOUT) }) describe('resend', () => { - let timestamps = [] - let published = [] + let timestamps: number[] = [] + let published: any[] = [] beforeEach(async () => { publishTestMessages = getPublishTestMessages(client, { @@ -1132,8 +1144,8 @@ describeRepeats('StreamrClient', () => { }) const publishedRaw = await publishTestMessages.raw(5) - timestamps = publishedRaw.map(([, raw]) => raw.streamMessage.getTimestamp()) - published = publishedRaw.map(([msg]) => msg) + timestamps = publishedRaw.map(([, raw]: any) => raw.streamMessage.getTimestamp()) + published = publishedRaw.map(([msg]: any) => msg) }) it('resend last', async () => { @@ -1177,7 +1189,7 @@ describeRepeats('StreamrClient', () => { }) it('works with message handler + resent event', async () => { - const messages = [] + const messages: any[] = [] const sub = await client.resend({ stream: stream.id, resend: { @@ -1190,6 +1202,7 @@ describeRepeats('StreamrClient', () => { await waitForEvent(sub, 'resent') expect(messages).toEqual(published.slice(-3)) }) + // @ts-expect-error }, 10000) describe('utf-8 encoding', () => { diff --git a/test/integration/SubscriberResends.test.js b/test/integration/SubscriberResends.test.ts similarity index 95% rename from test/integration/SubscriberResends.test.js rename to test/integration/SubscriberResends.test.ts index 5193dcfe9..82805a78a 100644 --- a/test/integration/SubscriberResends.test.js +++ b/test/integration/SubscriberResends.test.ts @@ -7,6 +7,8 @@ import Connection from '../../src/Connection' import { Defer } from '../../src/utils' import config from './config' +import { Stream } from '../../src/stream' +import { Subscriber } from '../../src/subscribe' const { ControlMessage } = ControlLayer @@ -18,13 +20,13 @@ const MAX_MESSAGES = 5 describeRepeats('resends', () => { let expectErrors = 0 // check no errors by default let onError = jest.fn() - let client - let stream - let published - let publishedRequests - let publishTestMessages - let waitForStorage - let subscriber + let client: StreamrClient + let stream: Stream + let published: any[] + let publishedRequests: any[] + let publishTestMessages: ReturnType + let waitForStorage: (...args: any[]) => Promise + let subscriber: Subscriber const createClient = (opts = {}) => { const c = new StreamrClient({ @@ -32,6 +34,7 @@ describeRepeats('resends', () => { auth: { privateKey: fakePrivateKey(), }, + // @ts-expect-error publishAutoDisconnectDelay: 10, autoConnect: false, autoDisconnect: false, @@ -75,7 +78,7 @@ describeRepeats('resends', () => { }) afterEach(async () => { - await wait() + await wait(0) // ensure no unexpected errors expect(onError).toHaveBeenCalledTimes(expectErrors) if (client) { @@ -98,7 +101,7 @@ describeRepeats('resends', () => { }) describe('no data', () => { - let emptyStream + let emptyStream: Stream it('throws error if bad stream id', async () => { await expect(async () => { @@ -181,8 +184,8 @@ describeRepeats('resends', () => { const results = await publishTestMessages.raw(MAX_MESSAGES, { waitForLast: true, }) - published = results.map(([msg]) => msg) - publishedRequests = results.map(([, req]) => req) + published = results.map(([msg]: any) => msg) + publishedRequests = results.map(([, req]: any) => req) }, WAIT_FOR_STORAGE_TIMEOUT * 2) beforeEach(async () => { @@ -246,6 +249,7 @@ describeRepeats('resends', () => { it('closes connection with autoDisconnect', async () => { client.connection.enableAutoConnect() + // @ts-expect-error client.connection.enableAutoDisconnect(0) // set 0 delay const sub = await subscriber.resend({ streamId: stream.id, @@ -278,7 +282,7 @@ describeRepeats('resends', () => { const onResent = Defer() const publishedBefore = published.slice() - const receivedMsgs = [] + const receivedMsgs: any[] = [] sub.on('resent', onResent.wrap(() => { expect(receivedMsgs).toEqual(publishedBefore) @@ -289,12 +293,12 @@ describeRepeats('resends', () => { const req = await client.publish(stream.id, newMessage) // should be realtime published.push(newMessage) publishedRequests.push(req) - let t + let t: ReturnType for await (const msg of sub) { receivedMsgs.push(msg.getParsedContent()) if (receivedMsgs.length === published.length) { await sub.return() - clearTimeout(t) + clearTimeout(t!) t = setTimeout(() => { // await wait() // give resent event a chance to fire onResent.reject(new Error('resent never called')) @@ -303,7 +307,7 @@ describeRepeats('resends', () => { } await onResent - clearTimeout(t) + clearTimeout(t!) expect(receivedMsgs).toHaveLength(published.length) expect(receivedMsgs).toEqual(published) @@ -353,7 +357,7 @@ describeRepeats('resends', () => { const onResent = Defer() const publishedBefore = published.slice() - const receivedMsgs = [] + const receivedMsgs: any[] = [] sub.once('resent', onResent.wrap(() => { expect(receivedMsgs).toEqual(publishedBefore) @@ -464,7 +468,8 @@ describeRepeats('resends', () => { }) it('can end inside resend', async () => { - const unsubscribeEvents = [] + const unsubscribeEvents: any[] = [] + // @ts-expect-error client.connection.on(ControlMessage.TYPES.UnsubscribeResponse, (m) => { unsubscribeEvents.push(m) }) diff --git a/test/integration/Subscription.test.js b/test/integration/Subscription.test.ts similarity index 91% rename from test/integration/Subscription.test.js rename to test/integration/Subscription.test.ts index bdcd8dd17..2c19259c9 100644 --- a/test/integration/Subscription.test.js +++ b/test/integration/Subscription.test.ts @@ -4,6 +4,8 @@ import { uid, fakePrivateKey } from '../utils' import { StreamrClient } from '../../src/StreamrClient' import config from './config' +import { Stream } from '../../src/stream' +import { Subscription } from '../../src/subscribe' const createClient = (opts = {}) => new StreamrClient({ ...config.clientOptions, @@ -22,13 +24,13 @@ const RESEND_ALL = { } describe('Subscription', () => { - let stream - let client - let subscription - let errors = [] + let stream: Stream + let client: StreamrClient + let subscription: Subscription + let errors: any[] = [] let expectedErrors = 0 - function onError(err) { + function onError(err: any) { errors.push(err) } @@ -39,9 +41,9 @@ describe('Subscription', () => { async function createMonitoredSubscription(opts = {}) { if (!client) { throw new Error('No client') } - const events = [] + const events: any[] = [] subscription = await client.subscribe({ - stream: stream.id, + streamId: stream.id, resend: RESEND_ALL, ...opts, }, (message) => { @@ -88,6 +90,7 @@ describe('Subscription', () => { it('fires events in correct order 1', async () => { const subscriptionEvents = await createMonitoredSubscription() await waitForEvent(subscription, 'resent') + // @ts-expect-error await client.unsubscribe(stream) expect(subscriptionEvents).toEqual([ 'resent', @@ -99,6 +102,7 @@ describe('Subscription', () => { const subscriptionEvents = await createMonitoredSubscription({ resend: undefined, }) + // @ts-expect-error await client.unsubscribe(stream) expect(subscriptionEvents).toEqual([ 'unsubscribed', diff --git a/test/integration/TokenBalance.test.ts b/test/integration/TokenBalance.test.ts index ce67b22b9..5764a35ba 100644 --- a/test/integration/TokenBalance.test.ts +++ b/test/integration/TokenBalance.test.ts @@ -11,9 +11,7 @@ import { until } from '../../src/utils' import debug from 'debug' import StreamrClient from '../../src' -// @ts-expect-error const providerMainnet = new providers.JsonRpcProvider(config.clientOptions.mainnet) -// @ts-expect-error const providerSidechain = new providers.JsonRpcProvider(config.clientOptions.sidechain) const tokenAdminMainnetWallet = new Wallet(config.tokenAdminPrivateKey, providerMainnet) const tokenAdminSidechainWallet = new Wallet(config.tokenAdminPrivateKey, providerSidechain) diff --git a/test/integration/authFetch.test.js b/test/integration/authFetch.test.ts similarity index 88% rename from test/integration/authFetch.test.js rename to test/integration/authFetch.test.ts index bb699a7c2..1ae08e867 100644 --- a/test/integration/authFetch.test.js +++ b/test/integration/authFetch.test.ts @@ -8,7 +8,7 @@ import { fakePrivateKey } from '../utils' import config from './config' describe('authFetch', () => { - let client + let client: StreamrClient afterEach(async () => { if (!client) { return } await client.ensureDisconnected() @@ -20,23 +20,29 @@ describe('authFetch', () => { it('sends Streamr-Client header', async () => { const realFetch = jest.requireActual('node-fetch') + // @ts-expect-error fetch.Response = realFetch.Response + // @ts-expect-error fetch.Promise = realFetch.Promise + // @ts-expect-error fetch.Request = realFetch.Request + // @ts-expect-error fetch.Headers = realFetch.Headers + // @ts-expect-error fetch.mockImplementation(realFetch) client = new StreamrClient({ + ...config.clientOptions, + autoConnect: false, + autoDisconnect: false, auth: { privateKey: fakePrivateKey() }, - autoConnect: false, - autoDisconnect: false, - ...config.clientOptions, }) await client.connect() expect(fetch).not.toHaveBeenCalled() // will get called in background though (questionable behaviour) await client.session.getSessionToken() // this ensures authentication completed expect(fetch).toHaveBeenCalled() + // @ts-expect-error fetch.mock.calls.forEach(([url, opts]) => { expect(typeof url).toEqual('string') expect(opts).toMatchObject({ diff --git a/test/integration/config.js b/test/integration/config.js index 338bde85f..fa4d49998 100644 --- a/test/integration/config.js +++ b/test/integration/config.js @@ -1,3 +1,7 @@ +const toNumber = (value) => { + return (value !== undefined) ? Number(value) : undefined +} + module.exports = { clientOptions: { // ganache 1: 0x4178baBE9E5148c6D5fd431cD72884B07Ad855a0 @@ -17,11 +21,11 @@ module.exports = { }, sidechain: { url: process.env.SIDECHAIN_URL || 'http://10.200.10.1:8546', - timeout: process.env.TEST_TIMEOUT, + timeout: toNumber(process.env.TEST_TIMEOUT), }, mainnet: { url: process.env.ETHEREUM_SERVER_URL || 'http://10.200.10.1:8545', - timeout: process.env.TEST_TIMEOUT, + timeout: toNumber(process.env.TEST_TIMEOUT), }, autoConnect: false, autoDisconnect: false, diff --git a/test/integration/dataunion/adminFee.test.ts b/test/integration/dataunion/adminFee.test.ts index d4c273a0e..326ba95e6 100644 --- a/test/integration/dataunion/adminFee.test.ts +++ b/test/integration/dataunion/adminFee.test.ts @@ -8,9 +8,7 @@ import config from '../config' const log = debug('StreamrClient::DataUnion::integration-test-adminFee') -// @ts-expect-error const providerSidechain = new providers.JsonRpcProvider(config.clientOptions.sidechain) -// @ts-expect-error const providerMainnet = new providers.JsonRpcProvider(config.clientOptions.mainnet) const adminWalletMainnet = new Wallet(config.clientOptions.auth.privateKey, providerMainnet) diff --git a/test/integration/dataunion/calculate.test.ts b/test/integration/dataunion/calculate.test.ts index cba46a0e4..0a0fdc40a 100644 --- a/test/integration/dataunion/calculate.test.ts +++ b/test/integration/dataunion/calculate.test.ts @@ -7,9 +7,7 @@ import { createClient, expectInvalidAddress } from '../../utils' const log = debug('StreamrClient::DataUnion::integration-test-calculate') -// @ts-expect-error const providerSidechain = new providers.JsonRpcProvider(config.clientOptions.sidechain) -// @ts-expect-error const providerMainnet = new providers.JsonRpcProvider(config.clientOptions.mainnet) const adminWalletMainnet = new Wallet(config.clientOptions.auth.privateKey, providerMainnet) diff --git a/test/integration/dataunion/deploy.test.ts b/test/integration/dataunion/deploy.test.ts index 123f273fa..1a9627859 100644 --- a/test/integration/dataunion/deploy.test.ts +++ b/test/integration/dataunion/deploy.test.ts @@ -7,9 +7,7 @@ import { createMockAddress } from '../../utils' const log = debug('StreamrClient::DataUnion::integration-test-deploy') -// @ts-expect-error const providerSidechain = new providers.JsonRpcProvider(config.clientOptions.sidechain) -// @ts-expect-error const providerMainnet = new providers.JsonRpcProvider(config.clientOptions.mainnet) describe('DataUnion deploy', () => { diff --git a/test/integration/dataunion/member.test.ts b/test/integration/dataunion/member.test.ts index 53c445e4e..569689fa2 100644 --- a/test/integration/dataunion/member.test.ts +++ b/test/integration/dataunion/member.test.ts @@ -10,9 +10,7 @@ import { getEndpointUrl } from '../../../src/utils' const log = debug('StreamrClient::DataUnion::integration-test-member') -// @ts-expect-error const providerSidechain = new providers.JsonRpcProvider(config.clientOptions.sidechain) -// @ts-expect-error const providerMainnet = new providers.JsonRpcProvider(config.clientOptions.mainnet) const joinMember = async (memberWallet: Wallet, secret: string|undefined, dataUnionAddress: string) => { diff --git a/test/integration/dataunion/signature.test.ts b/test/integration/dataunion/signature.test.ts index 8ef1b8e66..657ca60f5 100644 --- a/test/integration/dataunion/signature.test.ts +++ b/test/integration/dataunion/signature.test.ts @@ -11,7 +11,6 @@ import authFetch from '../../../src/rest/authFetch' const log = debug('StreamrClient::DataUnion::integration-test-signature') -// @ts-expect-error const providerSidechain = new providers.JsonRpcProvider(config.clientOptions.sidechain) const adminWalletSidechain = new Wallet(config.clientOptions.auth.privateKey, providerSidechain) diff --git a/test/integration/dataunion/stats.test.ts b/test/integration/dataunion/stats.test.ts index 786181d35..6555c9838 100644 --- a/test/integration/dataunion/stats.test.ts +++ b/test/integration/dataunion/stats.test.ts @@ -9,9 +9,7 @@ import { BigNumber } from '@ethersproject/bignumber' const log = debug('StreamrClient::DataUnion::integration-test-stats') -// @ts-expect-error const providerSidechain = new providers.JsonRpcProvider(config.clientOptions.sidechain) -// @ts-expect-error const providerMainnet = new providers.JsonRpcProvider(config.clientOptions.mainnet) describe('DataUnion stats', () => { diff --git a/test/integration/dataunion/withdraw.test.ts b/test/integration/dataunion/withdraw.test.ts index 9b5ac292d..672b3fd55 100644 --- a/test/integration/dataunion/withdraw.test.ts +++ b/test/integration/dataunion/withdraw.test.ts @@ -14,9 +14,7 @@ import { MemberStatus } from '../../../src/dataunion/DataUnion' const log = debug('StreamrClient::DataUnion::integration-test-withdraw') -// @ts-expect-error const providerSidechain = new providers.JsonRpcProvider(config.clientOptions.sidechain) -// @ts-expect-error const providerMainnet = new providers.JsonRpcProvider(config.clientOptions.mainnet) const adminWalletMainnet = new Wallet(config.clientOptions.auth.privateKey, providerMainnet) const adminWalletSidechain = new Wallet(config.clientOptions.auth.privateKey, providerSidechain) diff --git a/test/unit/Encryption.test.js b/test/unit/Encryption.test.ts similarity index 96% rename from test/unit/Encryption.test.js rename to test/unit/Encryption.test.ts index 5a52a1517..ba54f3d96 100644 --- a/test/unit/Encryption.test.js +++ b/test/unit/Encryption.test.ts @@ -13,9 +13,11 @@ function TestEncryptionUtil({ isBrowser = false } = {}) { beforeAll(() => { // this is the toggle used in EncryptionUtil to // use the webcrypto apis + // @ts-expect-error process.browser = !!isBrowser }) afterAll(() => { + // @ts-expect-error process.browser = !isBrowser }) @@ -62,10 +64,12 @@ function TestEncryptionUtil({ isBrowser = false } = {}) { const key = GroupKey.generate() const streamMessage = new StreamMessage({ messageId: new MessageID('streamId', 0, 1, 0, 'publisherId', 'msgChainId'), + // @ts-expect-error prevMesssageRef: null, content: { foo: 'bar', }, + // @ts-expect-error contentType: StreamMessage.CONTENT_TYPES.MESSAGE, encryptionType: StreamMessage.ENCRYPTION_TYPES.NONE, signatureType: StreamMessage.SIGNATURE_TYPES.NONE, @@ -80,10 +84,12 @@ function TestEncryptionUtil({ isBrowser = false } = {}) { const key = GroupKey.generate() const streamMessage = new StreamMessage({ messageId: new MessageID('streamId', 0, 1, 0, 'publisherId', 'msgChainId'), + // @ts-expect-error prevMesssageRef: null, content: { foo: 'bar', }, + // @ts-expect-error contentType: StreamMessage.CONTENT_TYPES.MESSAGE, encryptionType: StreamMessage.ENCRYPTION_TYPES.NONE, signatureType: StreamMessage.SIGNATURE_TYPES.NONE, @@ -165,7 +171,7 @@ function TestEncryptionUtil({ isBrowser = false } = {}) { it('validateGroupKey() throws if key is not a buffer', () => { expect(() => { - EncryptionUtil.validateGroupKey(ethers.utils.hexlify(GroupKey.generate())) + EncryptionUtil.validateGroupKey(ethers.utils.hexlify(GroupKey.generate() as any)) }).toThrow() }) diff --git a/test/unit/Scaffold.test.js b/test/unit/Scaffold.test.ts similarity index 91% rename from test/unit/Scaffold.test.js rename to test/unit/Scaffold.test.ts index 24a78b243..6f56c8bc3 100644 --- a/test/unit/Scaffold.test.js +++ b/test/unit/Scaffold.test.ts @@ -1,17 +1,18 @@ import Emitter from 'events' import { wait } from 'streamr-test-utils' +import { Todo } from '../../src/types' import { Defer } from '../../src/utils' import Scaffold from '../../src/utils/Scaffold' describe('Scaffold', () => { - let order - let up - let down - let emitter - let onDone - let onChange + let order: Todo + let up: Todo + let down: Todo + let emitter: Todo + let onDone: Todo + let onChange: Todo // const log = debug.extend('Scaffold') beforeEach(() => { @@ -23,30 +24,30 @@ describe('Scaffold', () => { const currentOrder = order emitter = new Emitter() - emitter.on('next', (name, v = '') => { + emitter.on('next', (name: Todo, v = '') => { const msg = `${name} ${v}`.trim() // log(msg) currentOrder.push(msg) }) const currentEmitter = emitter - up = async (...args) => { + up = async (...args: Todo[]) => { currentEmitter.emit('next', 'up start', ...args) await wait(50) currentEmitter.emit('next', 'up end', ...args) } - down = async (...args) => { + down = async (...args: Todo[]) => { currentEmitter.emit('next', 'down start', ...args) await wait(10) currentEmitter.emit('next', 'down end', ...args) } - onDone = (isUp) => { + onDone = (isUp: Todo) => { currentEmitter.emit('next', 'done', isUp ? 'up' : 'down') } - onChange = (isUp) => { + onChange = (isUp: Todo) => { currentEmitter.emit('next', 'change', isUp ? 'up' : 'down') } }) @@ -58,7 +59,7 @@ describe('Scaffold', () => { await up() return () => down() } - ], () => shouldUp, { + ], async () => shouldUp, { onDone, onChange }) @@ -98,7 +99,7 @@ describe('Scaffold', () => { shouldUp = false return () => down() } - ], () => shouldUp, { + ], async () => shouldUp, { onDone, onChange }) @@ -125,7 +126,7 @@ describe('Scaffold', () => { await up('b') throw err }, - ], () => true, { + ], async () => true, { onDone, onChange }) @@ -159,7 +160,7 @@ describe('Scaffold', () => { shouldThrow = true return () => down('b') }, - ], () => { + ], async () => { if (shouldThrow) { throw err } @@ -192,7 +193,7 @@ describe('Scaffold', () => { const err = new Error('expected') const currentEmitter = emitter - currentEmitter.on('next', (event, name) => { + currentEmitter.on('next', (event: Todo, name: Todo) => { if (event === 'down start' && name === 'c') { throw err // throw on down b } @@ -215,7 +216,7 @@ describe('Scaffold', () => { await down('c') // this should throw due to on('next' above } }, - ], () => shouldUp, { + ], async () => shouldUp, { onDone, onChange }) @@ -249,7 +250,7 @@ describe('Scaffold', () => { const err = new Error('expected') const currentEmitter = emitter - currentEmitter.on('next', (event, name) => { + currentEmitter.on('next', (event: Todo, name: Todo) => { if (event === 'down start' && name === 'a') { throw err // throw on down b } @@ -266,7 +267,7 @@ describe('Scaffold', () => { await down('b') } }, - ], () => shouldUp, { + ], async () => shouldUp, { onDone, onChange }) @@ -311,7 +312,7 @@ describe('Scaffold', () => { async () => { throw err } - ], () => shouldUp, { + ], async () => shouldUp, { onDone, onChange, onError: onErrorNoop, @@ -352,7 +353,7 @@ describe('Scaffold', () => { async () => { throw err } - ], () => shouldUp, { + ], async () => shouldUp, { onDone, onChange, onError: onErrorRethrow, @@ -385,7 +386,7 @@ describe('Scaffold', () => { await up() return () => down() } - ], () => shouldUp, { + ], async () => shouldUp, { onDone, onChange }) @@ -402,7 +403,7 @@ describe('Scaffold', () => { shouldUp = false return () => down() } - ], () => shouldUp, { + ], async () => shouldUp, { onDone, onChange }) @@ -426,7 +427,7 @@ describe('Scaffold', () => { await up() return () => down() } - ], () => true, { + ], async () => true, { onDone, onChange: () => { throw err @@ -446,7 +447,7 @@ describe('Scaffold', () => { await up() return () => down() } - ], () => shouldUp, { + ], async () => shouldUp, { onDone, onChange: (goingUp) => { onChange(goingUp) @@ -482,7 +483,7 @@ describe('Scaffold', () => { await up() return () => down() } - ], () => shouldUp, { + ], async () => shouldUp, { onDone, onChange: (goingUp) => { onChange(goingUp) @@ -517,11 +518,11 @@ describe('Scaffold', () => { await up() return () => down() } - ], () => shouldUp, { + ], async () => shouldUp, { onDone, onChange }) const done = Defer() - emitter.on('next', async (name) => { + emitter.on('next', async (name: Todo) => { if (name === 'up start') { shouldUp = false done.resolve(next()) @@ -545,8 +546,8 @@ describe('Scaffold', () => { }) describe('plays undo stack at point of state change', () => { - let shouldUp - let next + let shouldUp: Todo + let next: Todo const allUp = [ 'change up', 'up start a', @@ -606,10 +607,10 @@ describe('Scaffold', () => { it('can stop before first step', async () => { shouldUp = true const done = Defer() - emitter.on('next', async (name, v) => { + emitter.on('next', async (name: Todo, v: Todo) => { if (name === 'up start' && v === 'a') { shouldUp = false - done.resolve() + done.resolve(undefined) } }) @@ -632,10 +633,10 @@ describe('Scaffold', () => { it('can stop before second step', async () => { shouldUp = true const done = Defer() - emitter.on('next', async (name, v) => { + emitter.on('next', async (name: Todo, v: Todo) => { if (name === 'up end' && v === 'b') { shouldUp = false - done.resolve() + done.resolve(undefined) } }) @@ -662,10 +663,10 @@ describe('Scaffold', () => { it('can interrupt down while going down', async () => { const done = Defer() shouldUp = true - emitter.on('next', async (name, v) => { + emitter.on('next', async (name: Todo, v: Todo) => { if (name === 'down end' && v === 'b') { shouldUp = true - done.resolve() + done.resolve(undefined) } }) await next() @@ -694,23 +695,23 @@ describe('Scaffold', () => { const done3 = Defer() shouldUp = true let count = 0 - emitter.on('next', async (name, v) => { + emitter.on('next', async (name: Todo, v: Todo) => { if (name === 'down end' && v === 'b') { count += 1 shouldUp = true - done1.resolve() + done1.resolve(undefined) } if (name === 'change' && v === 'up' && count === 1) { count += 1 shouldUp = false - done2.resolve() + done2.resolve(undefined) } if (name === 'change' && v === 'down' && count === 2) { count += 1 shouldUp = true - done3.resolve() + done3.resolve(undefined) } }) await next() diff --git a/test/unit/Session.test.js b/test/unit/Session.test.ts similarity index 94% rename from test/unit/Session.test.js rename to test/unit/Session.test.ts index a31a7d40a..dd407b47e 100644 --- a/test/unit/Session.test.js +++ b/test/unit/Session.test.ts @@ -4,11 +4,12 @@ import { StreamrClient } from '../../src/StreamrClient' import { Defer } from '../../src/utils' import Session from '../../src/Session' import config from '../integration/config' +import { Todo } from '../../src/types' describe('Session', () => { - let session - let msg - let clientSessionToken + let session: Session + let msg: Todo + let clientSessionToken: Todo const createClient = (opts = {}) => new StreamrClient({ ...config.clientOptions, @@ -28,9 +29,11 @@ describe('Session', () => { session = new Session(clientSessionToken) session.options.unauthenticated = false session.loginFunction = sinon.stub() + // @ts-expect-error session.loginFunction.onCall(0).resolves({ token: 'session-token1', }) + // @ts-expect-error session.loginFunction.onCall(1).resolves({ token: 'session-token2', }) @@ -88,6 +91,7 @@ describe('Session', () => { describe('getSessionToken', () => { it('should set sessionToken', async () => { await session.getSessionToken() + // @ts-expect-error expect(session.loginFunction.calledOnce).toBeTruthy() expect(session.options.sessionToken === 'session-token1').toBeTruthy() }) @@ -95,12 +99,14 @@ describe('Session', () => { it('should not call loginFunction if token set', async () => { session.options.sessionToken = 'session-token1' await session.getSessionToken() + // @ts-expect-error expect(session.loginFunction.notCalled).toBeTruthy() }) it('should call loginFunction if new token required', async () => { session.options.sessionToken = 'expired-session-token' await session.getSessionToken(true) + // @ts-expect-error expect(session.loginFunction.calledOnce).toBeTruthy() expect(session.options.sessionToken === 'session-token1').toBeTruthy() }) @@ -112,6 +118,7 @@ describe('Session', () => { const p1 = session.getSessionToken() const p2 = session.getSessionToken() const [sessionToken1, sessionToken2] = await Promise.all([p1, p2]) + // @ts-expect-error expect(session.loginFunction.calledOnce).toBeTruthy() expect(sessionToken1).toEqual(sessionToken2) }) @@ -125,7 +132,7 @@ describe('Session', () => { describe('loginFunction rejects', () => { beforeEach(() => { - session = new Session() + session = new Session(undefined as any) session.options.unauthenticated = false msg = 'Error: Need either "privateKey", "ethereum", "apiKey" or "username"+"password" to login.' session.loginFunction = sinon.stub().rejects(new Error(msg)) @@ -141,6 +148,7 @@ describe('Session', () => { session.getSessionToken() )).rejects.toThrow(msg) ]) + // @ts-expect-error expect(session.loginFunction.calledOnce).toBeTruthy() }) @@ -151,6 +159,7 @@ describe('Session', () => { await expect(async () => ( session.getSessionToken() )).rejects.toThrow(msg) + // @ts-expect-error expect(session.loginFunction.calledTwice).toBeTruthy() }) }) diff --git a/test/unit/Signer.test.js b/test/unit/Signer.test.ts similarity index 94% rename from test/unit/Signer.test.js rename to test/unit/Signer.test.ts index 0751cdb20..351e33aea 100644 --- a/test/unit/Signer.test.js +++ b/test/unit/Signer.test.ts @@ -1,6 +1,7 @@ import { MessageLayer } from 'streamr-client-protocol' import Signer from '../../src/publish/Signer' +import { Todo } from '../../src/types' import { getAddressFromOptions } from '../../src/user' const { StreamMessage, MessageID, MessageRef } = MessageLayer @@ -14,6 +15,7 @@ describe('Signer', () => { const signer = Signer({ privateKey: '0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709', }) + // @ts-expect-error const signature = await signer.signData('some-data') expect(signature).toBeTruthy() }) @@ -27,11 +29,13 @@ describe('Signer', () => { it('Should noop if "never" option is set', async () => { const obj = {} + // @ts-expect-error expect(await Signer({}, 'never')(obj)).toBe(obj) }) it('Should noop when "auto" option is set with no private key or provider', async () => { const obj = {} + // @ts-expect-error expect(await Signer({}, 'auto')(obj)).toBe(obj) }) @@ -61,7 +65,7 @@ describe('Signer', () => { }) describe('signing', () => { - let signer + let signer: Todo const streamId = 'streamId' const data = { field: 'some-data', @@ -106,6 +110,7 @@ describe('Signer', () => { it('should sign StreamMessageV31 with non-null previous ref correctly', async () => { const address = await getAddressFromOptions(options) const streamMessage = new StreamMessage({ + // @ts-expect-error version: 31, messageId: new MessageID(streamId, 0, timestamp, 0, address, 'chain-id'), prevMsgRef: new MessageRef(timestamp - 10, 0), @@ -117,7 +122,7 @@ describe('Signer', () => { const payload = [ streamMessage.getStreamId(), streamMessage.getStreamPartition(), streamMessage.getTimestamp(), streamMessage.messageId.sequenceNumber, address.toLowerCase(), streamMessage.messageId.msgChainId, - streamMessage.prevMsgRef.timestamp, streamMessage.prevMsgRef.sequenceNumber, streamMessage.getSerializedContent() + streamMessage.prevMsgRef!.timestamp, streamMessage.prevMsgRef!.sequenceNumber, streamMessage.getSerializedContent() ] const expectedSignature = await signer.signData(payload.join('')) expect(payload.join('')).toEqual(streamMessage.getPayloadToSign()) diff --git a/test/unit/Stream.test.js b/test/unit/Stream.test.ts similarity index 87% rename from test/unit/Stream.test.js rename to test/unit/Stream.test.ts index 15f68dab6..2960a7d86 100644 --- a/test/unit/Stream.test.js +++ b/test/unit/Stream.test.ts @@ -1,8 +1,9 @@ import { Stream } from '../../src/stream' +import { Todo } from '../../src/types' describe('Stream', () => { - let stream - let clientMock + let stream: Stream + let clientMock: Todo beforeEach(() => { clientMock = { diff --git a/test/unit/StubbedStreamrClient.js b/test/unit/StubbedStreamrClient.ts similarity index 67% rename from test/unit/StubbedStreamrClient.js rename to test/unit/StubbedStreamrClient.ts index d1086d26f..2e4698184 100644 --- a/test/unit/StubbedStreamrClient.js +++ b/test/unit/StubbedStreamrClient.ts @@ -1,19 +1,22 @@ -import { StreamrClient } from '../../src/' +import { StreamrClient } from '../../src/index' import { Stream } from '../../src/stream' export default class StubbedStreamrClient extends StreamrClient { + // eslint-disable-next-line class-methods-use-this getUserInfo() { return Promise.resolve({ + name: '', username: 'username', }) } - async getStream () { - return new Stream(null, { + async getStream(): Promise { + return new Stream(this, { id: 'streamId', partitions: 1, }) } } // publisherId is the hash of 'username' +// @ts-expect-error StubbedStreamrClient.hashedUsername = '0x16F78A7D6317F102BBD95FC9A4F3FF2E3249287690B8BDAD6B7810F82B34ACE3'.toLowerCase() diff --git a/test/utils.ts b/test/utils.ts index 860c5fa9b..a77f0ce4f 100644 --- a/test/utils.ts +++ b/test/utils.ts @@ -4,6 +4,7 @@ import { providers, Wallet } from 'ethers' import { pTimeout, counterId, AggregatedError } from '../src/utils' import { validateOptions } from '../src/stream/utils' import { StreamrClient } from '../src/StreamrClient' +import { PublishRequest } from 'streamr-client-protocol/dist/src/protocol/control_layer' const crypto = require('crypto') const config = require('./integration/config') @@ -59,7 +60,7 @@ export function addAfterFn() { } } -export const Msg = (opts: any) => ({ +export const Msg = (opts?: any) => ({ value: uid('msg'), ...opts, }) @@ -131,7 +132,7 @@ export function getWaitForStorage(client: StreamrClient, defaultOpts = {}) { /* eslint-enable no-await-in-loop */ } -export function getPublishTestMessages(client: StreamrClient, defaultOpts = {}) { +export function getPublishTestMessages(client: StreamrClient, defaultOpts: any = {}) { // second argument could also be streamId if (typeof defaultOpts === 'string') { // eslint-disable-next-line no-param-reassign @@ -189,7 +190,7 @@ export function getPublishTestMessages(client: StreamrClient, defaultOpts = {}) try { client.connection.once('done', onDone) - const published = [] + const published: [ message: any, request: PublishRequest ][] = [] /* eslint-disable no-await-in-loop, no-loop-func */ for (let i = 0; i < n; i++) { checkDone() @@ -205,6 +206,7 @@ export function getPublishTestMessages(client: StreamrClient, defaultOpts = {}) checkDone() published.push([ message, + // @ts-expect-error request, ])