mtcute/e2e/ts/tests/05.worker.ts

86 lines
2.4 KiB
TypeScript
Raw Normal View History

2024-03-04 01:39:18 +03:00
/* eslint-disable no-restricted-imports */
import { expect } from 'chai'
import { describe, it } from 'mocha'
import path from 'path'
import { Worker } from 'worker_threads'
import { TelegramClient } from '@mtcute/core/client.js'
import { Message, TelegramWorkerPort, tl } from '@mtcute/node'
import { getApiParams, waitFor } from '../utils.js'
import type { CustomMethods } from './_worker.js'
describe('5. worker', async function () {
this.timeout(300_000)
const worker = new Worker(path.resolve(__dirname, '_worker.js'))
const port = new TelegramWorkerPort<CustomMethods>({
worker,
})
const portClient = new TelegramClient({ client: port })
it('should make api calls', async function () {
const res = await port.call({ _: 'help.getConfig' })
expect(res._).to.equal('config')
})
it('should call custom methods', async function () {
const hello = await port.invokeCustom('hello')
expect(hello).to.equal('world')
const sum = await port.invokeCustom('sum', 2, 3)
expect(sum).to.equal(5)
})
it('should throw errors', async function () {
try {
await port.call({ _: 'test.useError' })
throw new Error('should have thrown')
} catch (e) {
expect(e).to.be.an.instanceOf(tl.RpcError)
}
})
it('should receive updates', async function () {
const client2 = new TelegramClient(getApiParams('dc2.session'))
try {
await client2.connect()
await port.startUpdatesLoop()
const me = await portClient.getMe()
let username = me.username
if (!username) {
username = `mtcute_e2e_${Math.random().toString(36).slice(2, 8)}`
await portClient.setMyUsername(username)
}
const msgs: Message[] = []
portClient.on('new_message', (msg) => {
msgs.push(msg)
})
const testText = `test ${Math.random()}`
await client2.sendText(username, testText)
await waitFor(() => {
expect(msgs.length).to.be.greaterThan(0)
expect(msgs[0].text).to.equal(testText)
})
} catch (e) {
await client2.close()
throw e
}
await client2.close()
})
this.afterAll(async () => {
await port.close()
worker.terminate()
})
})