Skip to content

Commit d6dcde2

Browse files
committed
test(bot): ensure init retries after failure
1 parent af33162 commit d6dcde2

1 file changed

Lines changed: 83 additions & 0 deletions

File tree

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import test from 'node:test';
2+
import assert from 'node:assert/strict';
3+
import { Bot } from 'grammy';
4+
5+
test('ensureBotInit resets after init failure (no stuck rejected promise)', async (t) => {
6+
const originalInit = Bot.prototype.init;
7+
const originalHandleUpdate = Bot.prototype.handleUpdate;
8+
9+
let initCalls = 0;
10+
let handleUpdateCalls = 0;
11+
12+
Bot.prototype.init = async function initMock(): Promise<void> {
13+
initCalls += 1;
14+
if (initCalls === 1) throw new Error('init failed (simulated)');
15+
};
16+
17+
Bot.prototype.handleUpdate = async function handleUpdateMock(): Promise<void> {
18+
handleUpdateCalls += 1;
19+
};
20+
21+
t.after(() => {
22+
Bot.prototype.init = originalInit;
23+
Bot.prototype.handleUpdate = originalHandleUpdate;
24+
delete process.env.BOT_TOKEN;
25+
delete process.env.TELEGRAM_BOT_TOKEN;
26+
});
27+
28+
process.env.BOT_TOKEN = 'test-token';
29+
30+
// Import after env + prototype mocks so the module creates a bot using the patched methods.
31+
const mod = await import('./webhook.ts');
32+
const handler = mod.default as (
33+
req: { method: string; body?: unknown },
34+
res: {
35+
setHeader(name: string, value: string): void;
36+
status(code: number): { json(data: unknown): void; end(): void };
37+
end(): void;
38+
},
39+
) => Promise<void>;
40+
41+
function createRes() {
42+
let statusCode: number | null = null;
43+
let jsonBody: unknown = undefined;
44+
return {
45+
get statusCode() {
46+
return statusCode;
47+
},
48+
get jsonBody() {
49+
return jsonBody;
50+
},
51+
res: {
52+
setHeader() {},
53+
status(code: number) {
54+
statusCode = code;
55+
return {
56+
json(data: unknown) {
57+
jsonBody = data;
58+
},
59+
end() {},
60+
};
61+
},
62+
end() {},
63+
},
64+
};
65+
}
66+
67+
const update = JSON.stringify({
68+
update_id: 1,
69+
message: { chat: { id: 123 }, text: 'hi' },
70+
});
71+
72+
const first = createRes();
73+
await handler({ method: 'POST', body: update }, first.res);
74+
assert.equal(first.statusCode, 500);
75+
76+
const second = createRes();
77+
await handler({ method: 'POST', body: update }, second.res);
78+
assert.equal(second.statusCode, 200);
79+
80+
assert.equal(initCalls, 2);
81+
assert.equal(handleUpdateCalls, 1);
82+
});
83+

0 commit comments

Comments
 (0)